需求:將不規則二維陣列(每列長度不同)所有元素扁平化為一維陣列,排序後再填回原二維陣列結構。本文提供一個通用靜態方法 dyadicArraySort(int[][]),採用氣泡排序演示邏輯,實際專案建議改用 Arrays.sort 提升效能。
sum,建立一維陣列 n[sum]。Arrays.sort(n))。public class Array2DSort {
public static int[][] dyadicArraySort(int[][] a) {
if (a == null) return null;
// 1. 計算總長度
int total = 0;
for (int[] row : a) total += row.length;
// 2. 扁平化複製
int[] flat = new int[total];
int idx = 0;
for (int[] row : a) {
for (int val : row) flat[idx++] = val;
}
// 3. 排序(建議使用 Arrays.sort)
for (int i = 1; i < total; i++) {
for (int j = 0; j < total - i; j++) {
if (flat[j] > flat[j + 1]) {
int tmp = flat[j];
flat[j] = flat[j + 1];
flat[j + 1] = tmp;
}
}
}
// 4. 按原結構填回
idx = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = flat[idx++];
}
}
return a;
}
public static void main(String[] args) {
int[][] a = {{5,1,9,3,4,7,7}, {8,4,9,6,2}, {52}};
int[][] sorted = dyadicArraySort(a);
for (int[] row : sorted) {
System.out.print("{ ");
for (int v : row) System.out.print(v + " ");
System.out.println("}");
}
// 輸出:
// { 1 2 3 4 5 7 7 }
// { 7 8 9 9 52 }
// { 52 }
}
}
Arrays.sort(flat),時間複雜度從 O(n²) 降為 O(n log n)。Arrays.parallelSort(JDK 8+)。int[][] copy = Arrays.stream(a).map(int[]::clone).toArray(int[][]::new);。