Bubble sort on 2D Array Java -
string[][] 2darray = new string[counter][2]; 2darray [counter][column1] = string.valueof(counter); 2darray [counter][column2] = "something something"; for(int = 0; < 2darray.length-1; i++){ for(int j = + 1; j > 0; j--){ if(2darray[i][j] < 2darray[i-1][j]){ int[][] temp = 2darray[i-1][j]; 2darray[i-1][j] = 2darray[i][j]; 2darray[i][j] = temp; } } }
attempting sort array column 1 ascending. i've studied other references on here , mimic'd them reason ide not above...
if understand correctly, suggest following:
what need compare integer
values of array:
if(integer.valueof(2darray[i][0]) < integer.valueof(2darray[i-1][0])){
the reason don't include j
because sorting value of first column. 2darray[i][0]
gets value of counter
@ particular row.
i've seen other stuff in code use fixing:
for(int = 0; < 2darray.length; i++){ for(int j = i; j < 2darray.length; j++){ if(integer.valueof(2darray[j][0]) > integer.valueof(2darray[j+1][0])){ string temp[] = 2darray[j+1]; 2darray[j+1] = 2darray[j]; 2darray[j] = temp; } } }
this more in line think classic implementation of bubblesort:
private static void bubblesort(integer[] array) { (int = 0; < array.length; i++) { for(int j = 0; j < array.length - 1; j++) { if(array[j].compareto(array[j+1]) > 0) { swap(j, j+1, array); } } } } private static void swap(integer index1, integer index2, integer[] array) { if(index1 == index2)return; integer temp = new integer(array[index2]); array[index2] = array[index1]; array[index1] = temp; }
except in case, i'm treating array one-dimensional, since sorting 1 dimension.
Comments
Post a Comment