How to sort numbers in the first row then in the second one and finally in the third one in the ascending order by their columns values. For, example, I have the following array:
7 |10 |15 | 7 | 7
5 | 0 | 4 | 3 | 3
1 | 4 | 3 | 2 | 4
Then I need to transform it by sorting the first row but saving the columns order:
7 | 7 | 7 |10 |15
5 | 3 | 3 | 0 | 4
1 | 2 | 4 | 4 | 3
On the second iteration I should get something like this:
7 | 7 | 7 |10 |15
3 | 3 | 5 | 0 | 4
4 | 2 | 1 | 4 | 3
And, at the end:
7 | 7 | 7 |10 |15
3 | 3 | 5 | 0 | 4
2 | 4 | 1 | 4 | 3
I have the following code that sorts the first row and saving the columns order:
Integer k = column.size() - 1;
while (k > 1) {
Integer id = 0;
for (Integer j = 1; j <= k; j++)
if (listWithNumbers[0][j] > listWithNumbers[0][id])
id = j;
for (Integer i = 0; i < listWithNumbers.size(); i++) {
Integer max = listWithNumbers[i][id];
listWithNumbers[i][id] = listWithNumbers[i][k];
listWithNumbers[i][k] = max;
}
k -= 1;
}
And, I tried to rewrite the same code for sorting the second row but it doesn't sort correctly:
k = column.size() - 1;
while (k > 1) {
Integer id = 0;
for (Integer j = 1; j <= k; j++) {
if (listWithNumbers[0][j-1] == listWithNumbers[0][j])
id = j-1;
for (Integer i = 1; i < listWithNumbers.size(); i++) {
Integer max = listWithNumbers[i][id];
listWithNumbers[i][id] = listWithNumbers[i][k];
listWithNumbers[i][k] = max;
}
}
k -= 1;
}
If you do not need to have multiple iterations, EG do not have to print out the steps, then just create a single Comparator
that checks first row, then if the same checks the second, and so on...
Something like this:
public Comparator<Number[]> comp = (Number[] a, Number[] b) ->
{
for ( int i = 0; i < a.length; ++i )
if ( !a[i].equals( b[i] ) )
return a[i].compareTo( b[i] );
return 0;
}