Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort 2D array based on two columns

I have 2D array and it has 2 columns and I want to sort this.


input is this:

first column..... second column

3......................2

4......................9

3......................1

5......................0

1......................2


output is this:

first column..... second column

5......................0

4......................9

3......................2

3......................1

1......................2


I beginner in Java.

please help me whit a code of function(mySort(int[][] arr) to sort the array.

like image 784
Ali Avatar asked Jun 20 '26 01:06

Ali


1 Answers

You can sort with your custom comparator:

Arrays.sort(datas, new Comparator<Integer[]>() {
         @Override
         public int compare(Integer[] entry1, Integer[] entry2) {
                if(entry1[0] == entry2[0]){
                       return entry2[1] - entry1[1];
                }
                return entry2[0] - entry1[0];
         }
});
like image 159
Duy Tran Avatar answered Jun 21 '26 16:06

Duy Tran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!