简体   繁体   English

用3列对2d数组进行排序

[英]Sorting 2d array with 3 columns

Sort array by column like what i want to do here is to sort my values on my last row and depending on that sorting the number on the other colums might change too in the same row 像我在这里想要做的那样,按列对数组进行排序是对我的值进行最后一行的排序,并且根据排序的方式,同一行中其他列的数字也可能会更改

for example 例如

int[][] array= { {1, 5, 3},{2, 6, 4},{12, 10, 1},{30, 75, 1} };

and the output should be 并且输出应该是

{12, 10, 1} {30, 75, 1} {1, 5, 3} {2, 6, 4}

`System.out.println("Entre la cantidad de procesos que quiere correr: "); `System.out.println(“ Entr la cantidad de procesos que quiere correr:”); int pros = scan.nextInt(); 优点= scan.nextInt();

                int[][] myArr = new int[pros][3];

                for(int i=0; i< pros; i++){


                    System.out.println("CPU Burst proceso "+count+" :");
                     time2=scan.nextInt();

                     System.out.println("Arrival Time proceso "+count+" :"); 
                      arrt=scan.nextInt();


                      myArr[i][0]=count;
                      myArr[i][1]=time2;
                      myArr[i][2]=arrt;


                count++;
                }


                Arrays.sort(myArr, new Comparator<int[]>() {
                    public int compare(int[] o1, int[] o2) {
                        return Integer.compare(o2[2], o1[2]);
                    }
                });



                System.out.println(Arrays.deepToString(myArr)); `

You can use a custom Comparator to compare the arrays by the third element. 您可以使用自定义Comparator按第三个元素比较数组。

We could use the following comparator: 我们可以使用以下比较器:

(a1, a2) -> Integer.compare(a1[2], a2[2])

Which accepts two arrays as arguments and returns the result of Integer.compare() on their third elements. 它接受两个数组作为参数,并在第三个元素上返回Integer.compare()的结果。

For example: 例如:

int[][] array = {{1, 5, 3}, {2, 6, 4}, {12, 10, 1}, {30, 75, 1}};
Arrays.sort(array, (a1, a2) -> Integer.compare(a1[2], a2[2]));
System.out.println(Arrays.deepToString(array));

Output: 输出:

[[12, 10, 1], [30, 75, 1], [1, 5, 3], [2, 6, 4]]

Let's construct an auxiliary array whose length is the same as array.length : 让我们构造一个辅助数组,其长度与array.length相同:

int[] thirdColumnValues = new int[array.length];

Then we can copy the values of the third columns: 然后,我们可以复制第三列的值:

for(int i = 0; i < array.length; i++) {
  thirdColumnValues[i] = array[i][2];
}

Then we can sort this auxiliary array: 然后我们可以对这个辅助数组进行排序:

Arrays.sort(thirdColumnValues);

Then we can store the sorted values back into the original array: 然后,我们可以将排序后的值存储回原始数组中:

for(int i = 0; i < array.length; i++) {
  array[i][2] = thirdColumnValues[i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM