定制排序和比较器排序
案例1:二维数组排序(n行m列,按照某列或者某几列进行排序)
1.1按照二维数组的第一和第二列
public static void main(String[] args) {
int n = 10, m = 3;
int[][] arr = new int[n][m];
Random rand = new Random();
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
arr[i][j] = rand.nextInt(5);
}
}
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
System.out.print(arr[i][j] + ",");
}
System.out.println();
}
System.out.println("----我是分割线----");
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[0] == o2[0]){
return o1[1] - o2[1];
}
return o1[0] - o2[0];
}
});
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
System.out.print(arr[i][j] + ",");
}
System.out.println();
}
}
结果如下:
3,2,3,
2,4,1,
3,2,0,
4,0,1,
0,0,3,
0,3,1,
4,4,3,
4,3,1,
2,0,4,
1,1,0,
----我是分割线----
0,0,3,
0,3,1,
1,1,0,
2,0,4,
2,4,1,
3,2,3,
3,2,0,
4,0,1,
4,3,1,
4,4,3,