How can you sort a two-dimensional array in Java?
In Java, you can use the sort() method of the Arrays class to sort a two-dimensional array. Here is an example code:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] arr = {{5, 3, 2}, {9, 7, 1}, {8, 4, 6}};
// 对二维数组按行排序
for (int[] row : arr) {
Arrays.sort(row);
}
// 对二维数组按列排序
for (int i = 0; i < arr[0].length; i++) {
int[] column = new int[arr.length];
for (int j = 0; j < arr.length; j++) {
column[j] = arr[j][i];
}
Arrays.sort(column);
for (int j = 0; j < arr.length; j++) {
arr[j][i] = column[j];
}
}
// 输出排序后的二维数组
for (int[] row : arr) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
In the code above, the two-dimensional array is first sorted by rows and then by columns. Finally, the sorted two-dimensional array is output.