简体   繁体   中英

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: "); int pros = 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.

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.

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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