使用Arrays.sort()对自定义行数和列的二维数组进行排序

时间:2016-02-03 11:13:17

标签: java arrays sorting

我正在尝试使用Arrays.sort()以升序排序具有自定义行数和列数(Matrix)的二维数组。

我编写了一个示例(见下文),适用于具有任意行数和固定数量的列(3)的数组。是否可以将该示例扩展到任意数量的列?

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

    public class SortTest {

        public static String matrix2String (int[][] m){
            String[] str = new String[m.length];
            for(int i=0; i < str.length;i++){
                str[i] = Arrays.toString(m[i]);
            }
            return(Arrays.toString(str));
        } 

        //Matrix sorting currently restricted to 3 rows
        public static int[][] sortMatrix(int[][] m){
          Arrays.sort(m, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
               return Integer.compare(o1[2], o2[2]);
            }
          });

          Arrays.sort(m, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
               return Integer.compare(o1[1], o2[1]);
            }
          });

          Arrays.sort(m, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
               return Integer.compare(o1[0], o2[0]);
            }
          });

          return(m);
        }

        //Example
        public static void main(String[] args) {
            int[][] temp = {{ 2, 3, 3 }, { 2, 4, 5 },{ 1, 1, 5 }, 
                    { 2, 3, 2 },{ 3, 5, 9 }};

            System.out.println(Functions.matrix2String(temp));
        }

    }

输出:

   [[1, 1, 5], [2, 3, 2], [2, 3, 3], [2, 4, 5], [3, 5, 9]]

1 个答案:

答案 0 :(得分:1)

我自己找到了解决方案:

//The comparator now has to be defined outside Arrays.sort()
//or else the variable i is final and cannot be changed
public static Comparator<int[]> createComparator(int i){
    return new Comparator<int[]>() {
    @Override
      public int compare(int[] o1, int[] o2) {
       return Integer.compare(o1[i], o2[i]);
      }
    };
}

public static int[][] sortMatrix(int[][] m){
    for (int i=m[0].length-1; i>=0; i--){
        Arrays.sort(m, createComparator(i)); 
    }       
    return(m);
}