Reputation: 89
I'm trying to sort a matrix based on the values in the column. Is there any in-built way to do this, like Arrays.sort() or even if I turned it into a List and then did Collections.sort().
If not, what is the best way to implement the sort function myself? (I would define best as something that doesn't take too long to implement but also doesn't have a very slow runtime).
For example, if I have:
int[][] matrix:
[0, 30]
[5, 10]
[15, 20]
I want to sort it to (the column values were sorted):
[5, 10]
[15, 20]
[0, 30]
Another example:
int[][] matrix:
[7,10]
[2,4]
I want to sort it to (the column values were sorted):
[2,4]
[7,10]
Upvotes: 1
Views: 1492
Reputation: 2583
Arrays.sort(matrix, Comparator.comparingInt(row -> row[1]));
where 1 is column to sort by.
It sorts your outer array (which contains arrays of data) with Arrays.sort
. Values at a position [1] are compared in these rows to sort them properly. You can also compare by any other column, or row length, etc, like that:
Arrays.sort(matrix, Comparator.comparingInt(row -> row.length));
Upvotes: 0
Reputation: 34470
Just do:
Arrays.sort(matrix, Comparator.comparingInt(row -> row[1]));
This sorts rows by its 2nd column and assumes each row has at least 2 columns.
It uses Arrays.sort
and Comparator.comparingInt
to extract the 2nd component of each row.
Upvotes: 2