按列对2d数组进行排序

时间:2016-03-02 19:12:01

标签: java sorting multidimensional-array

这是我的代码,我有点失去了如何以我想要的方式使这项工作,我已经做到这样,用户将进入一个3x3 2d阵列,我试图排序每列但我很难找出它然后打印阵列,同时仍保持原件的粘性....

package newproject;

import java.util.Scanner;


public class ColumnSorting {
public static void main(String [] args){
    double a[][]=new double[3][3];
    Scanner input = new Scanner(System.in);

    for(int row=0;row<3;row++){

        for(int col=0;col<3;col++){
            System.out.println("Enter value: ");
            a[row][col]=input.nextDouble();
        }
    }
    displayArray(a);

}
public static void  displayArray(double x[][])    {
for (int row=0;row<x.length;row++) {
  for(int column = 0;column<x[row].length; column++) {
       System.out.print(x[row][column]+"\t");
 }
 System.out.println();
}
   }
       public static double[][] sortColumns(double[][] m){
         java.util.Arrays.sort(m, new java.util.Comparator<double[]>() {
             public int compare(double[] a, double[] b) {
               return Double.compare(a[0], b[0]);
    }
 });
}






}

1 个答案:

答案 0 :(得分:1)

取决于“按列排序”的含义。如果要独立处理每个列并对每个列进行排序,则以下代码将执行此操作:

    public static double[][] sortColumns(double[][] m) {
        int mrows = m.length;
        int mcols = m[0].length;
        double[][] retVal = new double[mrows][mcols];

        // process array column by column
        for (int i = 0; i < mcols; i++) {
            // copy column i from m into new array
            double[] mcol = new double[mrows];
            for (int j = 0; j < mrows; j++) 
               mcol[j] = m[j][i];

            // sort array
            Arrays.sort(mcol);

            // write sorted column to return value
            for (int j = 0; j < mrows; j++)
                retVal[j][i] = mcol[j];
        }

        return retVal;
    }

所以如果输入是:

1.0 2.0 3.0 
9.0 8.0 7.0 
5.0 8.0 3.0 

输出将是:

1.0 2.0 3.0 
5.0 8.0 3.0 
9.0 8.0 7.0

如果您希望按特定列值对矩阵的行进行排序,则以下代码将执行此操作:

    public static double[][] sortByColumns(double[][] m, int c) {
        int mrows = m.length;
        int mcols = m[0].length;
        double[][] retVal = new double[mrows][mcols];

        // copy into return value
        for (int i = 0; i < mrows; i++)
            retVal[i] = Arrays.copyOf(m[i], mcols);

        Arrays.sort(retVal, new Comparator<double[]>() {
            public int compare(double[] a, double[] b) {
                return Double.compare(a[c], b[c]);
            }
        });

        return retVal;
    }

所以如果输入是:

1.0 3.0 2.0 
7.0 4.0 9.0 
3.0 2.0 1.0

然后,如果我们按列1排序,那么输出将是:

3.0 2.0 1.0 
1.0 3.0 2.0 
7.0 4.0 9.0

这些解决方案中的每一个都会制作原始数组的副本,因此“保持原始阵列的完整性。”