共計 596 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用 Arrays 類的 sort 方法對二維數組進行排序。首先,需要將二維數組轉換為一維數組,然后再對一維數組進行排序。最后,再將排序后的一維數組轉換回二維數組。
以下是一個示例代碼:
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();}
}
}
運行上述代碼,將輸出排序后的二維數組。
丸趣 TV 網 – 提供最優質的資源集合!
正文完