EN
Java - sort 2D array
5
points
Using Java it is possible to sort 2D array in following way.
1. Index transformation example
package com.dirask.example;
public class Program {
public static void main(String[] args) {
int[][] array = {
{ 5, 3, 1 },
{ 8, -2, 0 },
{ 3, 7, 6 },
{ 9, 9, -3 }
};
// bubble sort example
for (int i = 0; i < 4 * 3; ++i) {
for (int j = 0; j < 4 * 3; ++j) {
int a = array[i / 3][i % 3];
int b = array[j / 3][j % 3];
if(a < b) {
array[i / 3][i % 3] = b;
array[j / 3][j % 3] = a;
}
}
}
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 3; ++j) {
System.out.print(" " + array[i][j]);
}
}
}
}
Output:
-3 -2 0 1 3 3 5 6 7 8 9 9