我有一个二维数组,其维度为myArray[x][3]
。我需要根据[x][0]
对数组进行排序。我正在使用Arrays.sort(myArray);
。那是有效的,然而,当时的数组是myArray[x]
的一维数组。然后我改变主意并将其改为二维数组。它填充了从1到9的整数。我已经搜索了对2维数组进行排序的清晰方法,并且找不到简单的解释。请帮忙。
感谢; 冰
好的,这是代码:
public static void sortArray(int myArray[][]){
Arrays.sort(myArray, new Comparator<Integer[]>(){
@Override
public int compare(Integer[] o1, Integer[] o2) {
return o1[0].compareTo(o2[0]);
}
});
这有用吗?
好的,这是问题所在。排序后的数组开始未排序,如下所示:
3 - 0 - 0
4 - 0 - 1
5 - 0 - 2
6 - 0 - 3
3 - 0 - 4
第一列[0][x]
是值,第二列[1][x]
是数组字段计数,最后一列[2][x]
是数组中的实际列号。整个方法从原始的二维数组中取出一整行,然后将其加载到一个3高x宽的数组中,然后根据[0][x]
列对数组进行排序。这是现在调用sort函数后的结果:
0 - 0 - 3
0 - 1 - 4
0 - 2 - 5
0 - 3 - 6
0 - 4 - 3
不知何故,我复制和粘贴的方法是交换数字,看起来排序是错误的。两个输出都使用相同的System.out.print
。
答案 0 :(得分:3)
如果我做对了:
Integer[][] numbers = new Integer[][]{{7, 8, 9}, {1, 2, 3}};
System.out.println("Before:");
for(Integer[] row : numbers) {
for(Integer num : row) {
System.out.print(num);
}
System.out.println("");
}
Arrays.sort(numbers, new Comparator<Integer[]>(){
@Override
public int compare(Integer[] o1, Integer[] o2) {
return o1[0].compareTo(o2[0]);
}
});
System.out.println("After:");
for(Integer[] row : numbers) {
for(Integer num : row) {
System.out.print(num);
}
System.out.println("");
}
打印:
Before: 789 123 After: 123 789
<强>更新强>
这正是你所需要的。
public static void sortArray(int myArray[][]) {
Arrays.sort(myArray, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.valueOf(o1[0]).compareTo(Integer.valueOf(o2[0]));
}
});
}
<强> UPDATE2:强>
对每一行进行排序:
public static void sortEachRow(int myArray[][]) {
for(int[] row : myArray) {
Arrays.sort(row);
}
}
答案 1 :(得分:0)
这应该有用。
public static void main(final String[] args)
{
Integer[][] numbers = new Integer[][] {{7, 8, 9}, {1, 2, 3}};
sortArray(numbers);
for (Integer[] s : numbers) {
System.out.println(s[0] + " " + s[1] + " " + s[2]);
}
}
public static void sortArray(Integer myArray[][])
{
Arrays.sort(myArray, new Comparator<Integer[]>()
{
@Override
public int compare(Integer[] o1, Integer[] o2)
{
return o1[0].compareTo(o2[0]);
}
});
}