2017-06-18 47 views
1

升序排列的所有元素一个二维数组有没有排序Java中的2维数组一样使用Arrays.sort()。对于前任何有效的方法: -如何排序在Java

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; 
        } 
       } 
      } 
     } 
    } 
+0

鉴于你的数组失去了一个零并获得了四,我认为它不算作排序。 –

+0

@ JoeC ..给我一个打字错误 – ani

+0

@Aominè那个帖子处理排序明智..我不想排序只有列......但整个阵列 – ani

回答

1

您可以先对所有元素进行排序,然后生成一对或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)); 
} 
+0

这是按O(n)时间复杂度排序的。右? – ani

+0

@ani this:https://stackoverflow.com/questions/31301471/big-o-complexity-of-java-util-stream-streamt-sorted –

+0

非常感谢你 – ani

1

您可以使用您解决问题:

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]] 

此解决方案将确保原始阵列的每个节点的相同的长度。

+0

可能需要查看此问答以获得更清晰的数据展平方法:https://stackoverflow.com/questions/2569279/how-to-flatten-2d-array- to-1d-array – christopher

+0

谢谢@christopher的链接 –