Is it possible to sort 2d-array by last row with Arrays.sort(,) in Java. The following snippet works great for sorting by last column but it doesn't seem to have a way to be adjusted for sorting by last row.
My first thought was to use tranforming columns to rows, doing sort and then transforming rows to column. Any better way for very big 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]);
}
});
Let's elaborate the whole situation: This is where I am when my array gets initialized and by rows and columns you can imagine this dataset as following:
{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
Sorting by last row means to rearrange the position of first and second column because 5 is bigger than 3. So after rearranging dataset it looks like:
2, 1, 3
7, 3, 11
9, 8, 16
2, 4, 8
3, 5, 9 //now it's ordered by last row (first and second column have changed they position, by chance third column is in a right place already)