How to sort and output a two-dimensional array in Java?
In Java, you can sort a two-dimensional array using the sort method from the Arrays class. Initially, you must convert the two-dimensional array into a one-dimensional array, sort the one-dimensional array, and then convert it back to a two-dimensional array.
Here is a sample code:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] arr = { { 5, 7, 1 }, { 8, 4, 6 }, { 3, 9, 2 } };
int rows = arr.length;
int cols = arr[0].length;
int[] temp = new int[rows * cols];
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
temp[index++] = arr[i][j];
}
}
Arrays.sort(temp);
index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = temp[index++];
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Running the above code will output the sorted two-dimensional array.