二维数组按某列排序

二维数组按指定列排序(升序):

输入:
5
7
2 5 2 87 23 12 51
9 78 12 76 12 87 1
98 76 456 12 421 987 20
76 12 0 89 56 524 222
999 123 5 412 88 225 81
5
输出(按第6列排序后):
2 5 2 87 23 12 51 
9 78 12 76 12 87 1 
999 123 5 412 88 225 81 
76 12 0 89 56 524 222 
98 76 456 12 421 987 20 

代码如下:

package huawei.merru.cs.swjtu;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class arrSort {
  
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        int row = 0;
        int col = 0;
        int row0 = 0; //总行数,不会随输入时的row--而变
        boolean flag = false;
        int index = 0;
        int sortcol = 0;
    
        
        String[][] unsort = null;
        
        while(true){
            if(row < 0) {
                sortcol = Integer.parseInt(in.nextLine()); //按该列排序
                break;
            }
            if(flag == false){
                row = Integer.parseInt(in.nextLine()) - 1;  //特别注意此次,为终止循环做准备
                row0 = row + 1;
                col = Integer.parseInt(in.nextLine());
                unsort = new String[row + 1][col];  //注意位置
                flag = true;
            }
            //unsort = new String[row][col];
            unsort[index] = in.nextLine().split(" ");
            index++;
            row--;
        }
        
        
        sort(unsort,sortcol);
        System.out.println("排序后:");
        for(int i=0;i<row0;i++){
        for(int j=0;j<col;j++){
            System.out.print(unsort[i][j]+" ");
        }
        System.out.println();
        
    }
    }
    public static void sort(String[][] unsort,final int sortcol){ //sortcol 必须是final类型的
        
        Arrays.sort(unsort, 
                new Comparator<String[]>() {

                    @Override
                    public int compare(String[] o1, String[] o2) {
                        // TODO Auto-generated method stub
                        if(Integer.parseInt(o1[sortcol]) < Integer.parseInt(o2[sortcol])){
                            return -1;
                        }else if(Integer.parseInt(o1[sortcol]) > Integer.parseInt(o2[sortcol])) {
                            return 1;
                        }else{
                            return 0;
                        }
                        
                    }
                }        
                );
        
    }
}

总结:

   * 1、由于是对数组对象排序,因此不能用Comparable接口(内部排序)。只能用Comparator接口(外部排序)。
   * 2、排序要使用参数,所以只能用内部类实现Comparator接口。


不知以上两点总结是否有错误?
posted @ 2015-07-20 15:49  MERRU  阅读(2366)  评论(0编辑  收藏  举报