Below is the code for sorting a 2D array, the trick is that you should think of the 2D array as a single array, and then output the corresponding rows, offset pairs for the indices.
import java.util.Arrays;
public class Bubble2DSort {
public static void main(String[] args) {
System.out.println("Started");
int[][] matrix = {{49,44,54,55,100,344}, {1,1,2,6,12,32}};
sortMatrix(matrix);
System.out.println("Printing output ");
for(int[] rowArr : matrix) {
System.out.println(Arrays.toString(rowArr));
}
}
private static void sortMatrix(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int totalCount = row * col;
System.out.println("totalCount : " +totalCount);
boolean noSwaps = false;
for(int i = 0; !noSwaps; i++) {
noSwaps = true;
for(int j = 1; j < totalCount - i; j++) {
int currentRow = (j-1) / col;
int currentOffset = (j-1) % col;
int nextRow = j / col;
int nextOffset = j % col;
if( matrix[currentRow][currentOffset] > matrix[nextRow][nextOffset]) {
int temp = matrix[nextRow][nextOffset];
matrix[nextRow][nextOffset] = matrix[currentRow][currentOffset];
matrix[currentRow][currentOffset] = temp;
noSwaps = false;
}
}
}
}
}
Output:
Started
totalCount : 12
Printing output
[1, 1, 2, 6, 12, 32]
[44, 49, 54, 55, 100, 344]
source
share