實現對一個二維數組按指定的列集進行排序

#  private int array[][] = new int[][] {  
#             { 12, 34, 68, 32, 9, 12, 545 }, 
#             { 34, 72, 82, 57, 56, 0, 213 },  
#             { 12, 34, 68, 32, 21, 945, 23 }, 
#             { 91, 10, 3, 2354, 73, 34, 18 },  
#             { 12, 83, 189, 26, 27, 98, 33 }, 
#             { 47, 23, 889, 24, 899, 23, 657 }, 
#             { 12, 34, 68, 343, 878, 235, 768 }, 
#             { 12, 34, 98, 4, 56, 78, 12}, 
#             { 26, 78, 2365, 78, 34, 256, 873 } };// 要排序的數組

實現對一個二維數組按指定的列集進行排序。要求實現類似sql中order by的功能,移動時,整行移動,不能打亂整行順序。可將二維數組想象成數據庫裏的一個表記錄集,
然後按指定的列集進行排序,即order by col1,col2。

 

這是在論壇中看到的一道筆試題,自己寫了個又臭又長的code.看得自己都覺得不好意思了,深知自己java基礎還很弱。

下面是一個網友的code.很簡潔、明瞭。貼在下面了。

package test;
  import java.util.Arrays;  
import java.util.Comparator;  
    
  public class ArraySort {  
    
      public static void sort(int[][] ob, final int[] order) {  
          Arrays.sort(ob, new Comparator<Object>() {  
              public int compare(Object o1, Object o2) {  
                  int[] one = (int[]) o1;  
                  int[] two = (int[]) o2;  
                  for (int i = 0; i < order.length; i++) {  
                      int k = order[i];  
                      if (one[k] > two[k]) {  
                          return 1;  
                      } else if (one[k] < two[k]) {  
                          return -1;  
                      } else {  
                          continue;  //如果按一條件比較結果相等,就使用第二個條件進行比較。
                      }  
                  }  
                  return 0;  
              }  
          }); 
      }  
    
      public static void main(String[] args) {  
          int array[][] = new int[][] {   
                  { 12, 34, 68, 32, 9, 12, 545 },   
                  { 34, 72, 82, 57, 56, 0, 213 },   
                  { 12, 34, 68, 32, 21, 945, 23 },   
                  { 91, 10, 3, 2354, 73, 34, 18 },  
                  { 12, 83, 189, 26, 27, 98, 33 },   
                  { 47, 23, 889, 24, 899, 23, 657 },   
                  { 12, 34, 68, 343, 878, 235, 768 },   
                  { 12, 34, 98, 56, 78, 12, 546 },   
                  { 26, 78, 2365, 78, 34, 256, 873 } };  
          sort(array, new int[] {0,1,3});  
          for (int i = 0; i < array.length; i++) {  
              for (int j = 0; j < array[i].length; j++) {  
                  System.out.print(array[i][j]);  
                  System.out.print("\t");  
              }  
              System.out.println();  
          }  
      }  
  }
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章