Is it possible to sort a 2d array by last row using Arrays.sort (,) in Java. The following snippet is great for sorting by the last column, but it seems that it cannot be configured to sort by the last row.
My first thought was to use converting columns to rows, doing sorting, and then converting rows to column. Any better way for very large arrays?
int[][] twoDim = { {1, 2, 3}, {3, 7, 11}, {8, 9, 16}, {4, 2,8}, {5, 3, 9} };
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o1[2]).compareTo(o2[2]);
}
});
Think over the whole situation: This is where I, when my array is initialized, and you can represent this data set in rows and columns as follows:
{1, 2, 3}, //first row with three columns
{3, 7, 11}, //second row with three columns
{8, 9, 16},
{4, 2, 8},
{5, 3, 9} //last row with three columns
, 5 3. , :
2, 1, 3
7, 3, 11
9, 8, 16
2, 4, 8
3, 5, 9 //now it ordered by last row (first and second column have changed they position, by chance third column is in a right place already)