簡體   English   中英

如何在Java中以所有元素升序對二維數組進行排序

[英]How to sort a 2 dimensional array with all elements in ascending order in java

是否有任何有效的方法可以像使用Arrays.sort()一樣在Java中對二維數組進行Arrays.sort() 。例如:

a={{3 ,1},{0,2})
result={{0,1},{2,3}}

這是我的方法:

  for (int x = 0; x < n; x++) {
      for (int y = 0; y < n; y++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (grid[i][j] > grid[x][y]) {
                        int t = grid[x][y];
                        grid[x][y] = grid[i][j];
                        grid[i][j] = t;
                    }
                }
            }
        }
    }

您可以使用以下方法解決問題:

public static void main(String[] args) {
    Integer[][] a = {{3, 1}, {0, 2}};
    List<Integer> list = new ArrayList<>();
    for (Integer[] i : a) {//<--convert the 2d to list-------------------------(1)
        list.addAll(Arrays.asList(i));
    }
    Collections.sort(list);//<--sort this list---------------------------------(2)
    Integer[][] result = new Integer[a.length][];//create new 2d array---------(3)
    int k = 0;
    for (int i = 0; i < a.length; i++) {//loop throw the original array--------(4) 
        //creae temp array with the same size of each 1d array-----------------(5)
        Integer[] temp = new Integer[a[i].length];
        //loop and fill temp array with elements of the list-------------------(6)
        for (int j = 0; j < a[i].length; j++) {
            temp[j] = list.get(k);
            k++;
        }
        result[i] = temp;//add the temp to the new array-----------------------(7)
    }

    System.out.println(Arrays.deepToString(result));//print the new array
}

input                                           output
{{3, 1}, {0, 2}}                                [[0, 1], [2, 3]]
{{3, 1, 5}, {0, 2}}                             [[0, 1, 2], [3, 5]]     
{{3, 1, 5}, {0, 5}, {3, 7, 5}, {10, 9, 11}}     [[0, 1, 3], [3, 5], [5, 5, 7], [9, 10, 11]]

請注意,此解決方案將確保原始數組的每個節點的長度相同。

您可以先對所有元素進行排序,然后生成對或n元素,例如;

int[][] a={{3 ,1},{0,2}};
int count = a[0].length;

//Sort the elements
List<Integer> sortedElements = Arrays.stream(a)
    .flatMapToInt(e -> Arrays.stream(e))
    .boxed()
    .sorted()
    .collect(Collectors.toList());

//Now, generate 2D arrays
int[][] arrays = new int[a.length][];
int[] temp = new int[count];
int index = 0;
for(int i = 0; i < sortedElements.size() ; i++){
    if(i % count == 0 && i != 0){
        arrays[index++] = temp;
        temp = new int[count];
    }
    temp[i % count] = sortedElements.get(i);
}
arrays[index++] = temp;

for(int[] e : arrays){
    System.out.println(Arrays.toString(e));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM