I have a 2D array with 8 columns (col0-col7) and a thousand rows that I would like to sort ascending on 2 columns: col2 and col3. I would like to give priority to column col2 and first sort on that column. If two values in col2 are equal (very high chance) then I would like to sort based on col3. This is the current code I use:
public static void sortMyArray() {
Arrays.sort(myArray, new Comparator<double[]>() {
public int compare(double[] a, double[] b) {
int result = Double.compare(a[2], b[2]);
if (result == 0) {
return Double.compare(a[3], b[3]);
} else {
return result;
}
}
});
}
The current code I use sorts my array only on col3. I would like to stick to an 2d array due to later calculations.
Hopefully you can help me.
EDIT: made a few changes based on feedback from a user (for which many thanks!). However, the problem remains. This is the code I used to test the snippet:
public static void loadTotalData() {
for (int i = 0; i < myArray.length; i++) {
myArray[i][0] = classOriginal.allData[i].col0data;
myArray[i][1] = classOriginal.allData[i].col1data;
myArray[i][2] = classOriginal.allData[i].col2data;
myArray[i][3] = classOriginal.allData[i].col3data;
myArray[i][4] = 0.0;
myArray[i][5] = 0.0;
myArray[i][6] = 0.0;
myArray[i][7] = 0.0;
}
System.out.println(myArray[0][3]);
System.out.println(myArray[1][3]);
System.out.println(myArray[2][3]);
System.out.println(myArray[3][3]);
System.out.println(myArray[4][3]);
System.out.println(myArray[5][3]);
System.out.println(myArray[6][3]);
System.out.println(myArray[7][3]);
System.out.println(myArray[8][3]);
System.out.println(myArray[9][3]);
System.out.println(myArray[10][3]);
classForSortingAndLoading.sortMyArray();
System.out.println(myArray[0][3]);
System.out.println(myArray[1][3]);
System.out.println(myArray[2][3]);
System.out.println(myArray[3][3]);
System.out.println(myArray[4][3]);
System.out.println(myArray[5][3]);
System.out.println(myArray[6][3]);
System.out.println(myArray[7][3]);
System.out.println(myArray[8][3]);
System.out.println(myArray[9][3]);
System.out.println(myArray[10][3]);
Probably not the most efficient way to test this, but I know the data source and thus I know what it should give back before and after the sorting.