Java 根据列对二维整数数组进行排序的过程
我之前拥有的数组以及排序后需要的数组: 之前:Java 根据列对二维整数数组进行排序的过程,java,arrays,matrix,integer,Java,Arrays,Matrix,Integer,我之前拥有的数组以及排序后需要的数组: 之前: Box Weight Priority 1 50 5 2 30 8 3 90 6 4 20 7 5 80 9 之后: Box Weight Priority 3 90 6 5 80 9 1 50
Box Weight Priority
1 50 5
2 30 8
3 90 6
4 20 7
5 80 9
之后:
Box Weight Priority
3 90 6
5 80 9
1 50 5
2 30 8
4 20 7
我们在int矩阵中工作:
data= new int[BoxNumber][3];
排序基于第二列的权重。我正在寻找一个对数据数组进行排序的过程
public void sortC(int[][] temp)
{
if (temp.length >= 2)
{
for (int i = 1; i <= temp.length - 1; i++)
{
int[] hold = temp[i];
int[] holdP = temp[i-1];
int j = i;
while (j > 0 && hold[1] < holdP[1]) // 1 represents the reference of sorting
{
hold = temp[j];
holdP = temp[j-1];
temp[j] = holdP;
temp[j-1] = hold;
j--;
}
}
}
}
sortC(data);
public void sortC(int[]temp)
{
如果(温度长度>=2)
{
for(int i=1;i 0&&hold[1]
我尝试了这个,但不幸的是它没有给出正确的排序,我无法找出pickle。您可以这样做,而不是编写自己的排序算法:
int[][] n = new int[10][];
//init your array here
List<int[]> ints = Arrays.asList(n);
Collections.sort(ints, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1]; // compare via second column
}
});
使用带有自定义比较器的
java.util.array.sort
int[][] temp = { { 1, 50, 5 }, { 2, 30, 8 }, { 3, 90, 6 },
{ 4, 20, 7 }, { 5, 80, 9 }, };
Arrays.sort(temp, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[1], o1[1]);
}
});
sort(boxTypes,(a,b)->b[1]-a[1])
或者使用优先级队列
PriorityQueue=newpriorityqueue((a,b)->b[1]-a[1]) 有没有其他方法可以纠正我提到的程序?因为我不擅长列表和集合?u给出的
数组的方法。sort
非常有效。你能不能给我提一些意见来解释一下这个方法,因为我不太擅长比较和数组。排序工具?谢谢你的支持help@GhassenBellaghaJava文档:在Java8中,Arrays.sort(temp、Comparator.comparingit(arr->arr[1])代码>@shmosel谢谢。从未重读过这篇文章。
int[][] temp = { { 1, 50, 5 }, { 2, 30, 8 }, { 3, 90, 6 },
{ 4, 20, 7 }, { 5, 80, 9 }, };
Arrays.sort(temp, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[1], o1[1]);
}
});
Arrays.sort(temp, Comparator.comparingInt(arr -> arr[1]));