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

Gha*_*gha 6 java arrays int matrix

我将向您展示一个关于问题目的的例子.我之前拥有的数组以及排序后我们想要的数据:

之前:

Box    Weight    Priority
1       50          5
2       30          8
3       90          6
4       20          7  
5       80          9
Run Code Online (Sandbox Code Playgroud)

之后:

Box    Weight    Priority
3       90          6
5       80          9
1       50          5
2       30          8
4       20          7
Run Code Online (Sandbox Code Playgroud)

我们在int矩阵中工作:

data= new int[BoxNumber][3];
Run Code Online (Sandbox Code Playgroud)

排序基于第二列Weight.Am寻找对数据数组进行排序的过程.

 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);
Run Code Online (Sandbox Code Playgroud)

我试过这个,但不幸的是没有给出正确的排序我无法弄清楚泡菜.一些帮助PLZ?

joh*_*902 7

使用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]);
    }
});
Run Code Online (Sandbox Code Playgroud)

作为shmosel 下文提到的,与Java 8中,您可以使用:

Arrays.sort(temp, Comparator.comparingInt(arr -> arr[1]));
Run Code Online (Sandbox Code Playgroud)