【问题标题】:Procedure to sort a two dimensional int array depending on column根据列对二维 int 数组进行排序的过程
【发布时间】:2013-08-16 11:13:47
【问题描述】:

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

之前:

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 arrays matrix integer


    【解决方案1】:

    您可以这样做,而不是编写自己的排序算法:

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

    如果你想再次使它成为数组:

    int[][] result = ints.toArray(n);
    

    【讨论】:

    • 还有其他方法可以纠正我提到的程序吗?因为不擅长列表和集合..?
    【解决方案2】:

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

    【讨论】:

    • 你给Arrays.sort 的方法非常有效。您能否提及一些 cmets 来为我解释该方法,因为我不擅长 Comparator 和 Arrays.sort 工具?并感谢您的帮助
    • @GhassenBellagha Java 文档:Arrays.sort
    • 在 Java 8 中,Arrays.sort(temp, Comparator.comparingInt(arr -&gt; arr[1]));
    • @shmosel 谢谢。再也没有重温这篇文章。
    【解决方案3】:

    Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]);

    或使用优先队列

    PriorityQueue queue = new PriorityQueue((a, b)->b[1] - a[1]);

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 2022-01-10
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      相关资源
      最近更新 更多