2016-03-02 101 views
-4

這裏是我的代碼,即時有點失去了如何使這個工作的方式我想,我已經做到了,所以用戶將進入一個3x3二維數組,即時嘗試排序每列但有IM很難計算出來,然後打印陣列,同時仍保持原來的粘性....按列排序一個二維數組

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]); 
    } 
}); 
} 






} 
+0

大頭貼==完好無損嗎? – Idos

+0

究竟是什麼讓你失望?你的問題並不清楚你想如何對每列進行排序,或者在哪一點你感到困惑。它是理論,編碼部分還是兩者? – Tricky12

+0

*「對每列進行排序」*是什麼意思?標題說排序*「按列」*,這是完全不同的獨立排序每列。 – Andreas

回答

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 

這些解決方案使原始數組的一個副本,因此「保持原始數組的完整性」。