I have a 2 dimensional array, that has dimensions of myArray[x][3]
. I need to sort the array based upon [x][0]
. I was using Arrays.sort(myArray);
. That was working, however, the array at the time was a one dimension array of myArray[x]
. Then I changed my mind and changed it into a 2 dimensional array. It is filled with integers from 1 to 9. I have searched for the clear method to sort 2 dimensional arrays, and cannot find the simple explanations. Please help.
Thanks; Ice
Ok, here is the code:
public static void sortArray(int myArray[][]){
Arrays.sort(myArray, new Comparator<Integer[]>(){
@Override
public int compare(Integer[] o1, Integer[] o2) {
return o1[0].compareTo(o2[0]);
}
});
Did that work?
OK, here is the problem. The sorted array starts out unsorted, like this:
3 - 0 - 0
4 - 0 - 1
5 - 0 - 2
6 - 0 - 3
3 - 0 - 4
The first column [0][x]
is the value, the second column [1][x]
is the array field count, and the last column [2][x]
is the actual column number in the array. The overall method, takes a entire row from the original 2 dimensional array, and loads it into a 3-tall by x-wide array, then sorts the array based on the [0][x]
column. Here is the result after the sort function now being called:
0 - 0 - 3
0 - 1 - 4
0 - 2 - 5
0 - 3 - 6
0 - 4 - 3
Somehow, the method I copied and pasted, is swapping out the numbers, seems like the sorting is wrong. Same System.out.print
is being used on both outputs.