繁体   English   中英

如何对二维数组排序?

[英]How to Sort a 2Dimensional array?

我需要按升序对二维数组进行排序。

例:

之前:

5.1            3.3

6.3            4.8

4.9            6.9

7.4            5.2

3.6            7.4

后:

3.6            3.3

4.9            4.8

5.1            5.2   

6.3            6.9   

7.4            7.4 
I think first you convert your 2D array into 1D than sorted your array after that
again convert it into 1D to 2D and another way is to sort you array

 List<Double> ar = new ArrayList<>();
    for(int i=0;i<array.length;i++){
        for(int j=0;j<array[i].length;j++){
            ar.add(a[i][j]);
        }
    }
    Collections.sort(ar);
    for (Double double1 : ar) {
        System.out.println(double1);
    }
}

输出为3.3 3.6 4.8 4.9 5.1 5.2 6.3 6.9 7.4 7.4

您可以使用Arrays#Sort(T [] a,Comparator c)尝试这样:

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
    public int compare(double[] a, double[] b) {
        return Double.compare(a[0], b[0]);
    }

先前的答案

double[][] array = {
                    {5.1, 3.3}, 
                    {6.3, 4.8}, 
                    {4.9, 6.9}, 
                    {7.4, 5.2}, 
                    {3.6, 7.4}, 
                   };
// for the number of columns in each row (2D so 0 and 1)
for (int col = 0; col <= 1; col++) {

    // create a temporary array to store this column in the 2D array
    double[] thisColumn = new double[array.length];

    // asign the temporary column values
    for (int row = 0; row < array.length; row++) {
        thisColumn[row] = array[row][col];
    }

    // sort that column
    Arrays.sort(thisColumn);

    // reassign it back to the original array
    for (int row = 0; row < array.length; row++) {
         array[row][col] = thisColumn[row];
    }
}
// print it out
for (double[] r : array) {
    for (double c : r) {
        System.out.print(c + "\t");
    }
    System.out.println();
}

输出:

3.6    3.3  
4.9    4.8  
5.1    5.2  
6.3    6.9  
7.4    7.4  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM