如何对2维数组进行排序?

时间:2014-02-26 05:34:51

标签: java arrays sorting

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

示例:

在:

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 

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以尝试使用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]);
    }

答案 2 :(得分:1)

Previous answer

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