gpt4 book ai didi

java - 根据列对二维 int 数组进行排序的过程

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:06:12 26 4
gpt4 key购买 nike

我之前的数组以及排序后我们想要的数组:

之前:

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);

我试过这个,但不幸的是它没有给出正确的排序我无法弄清楚泡菜。

最佳答案

java.util.Arrays.sort 与自定义 Comparator 结合使用。

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]);
}
});

作为 shmosel mentioned below ,对于 Java 8,您可以使用:

Arrays.sort(temp, Comparator.comparingInt(arr -> arr[1]));

关于java - 根据列对二维 int 数组进行排序的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18232788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com