Ali
Ali

Reputation: 155

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.

Upvotes: 3

Views: 5897

Answers (4)

Beri
Beri

Reputation: 11600

When using java 8, you can also do it like this:

    Comparator<int[]> comparator = Comparator.<int[]>comparing(x -> x[0])
    .thenComparing(x -> x[1]);
    // when
    Arrays.sort(a, comparator.reversed());

Upvotes: 3

djklicks-dhananjay
djklicks-dhananjay

Reputation: 29

For a n*2 array

Sorting based on column1 (ascending)

    Arrays.sort(arr, (a,b)-> {
            if(a[0] == b[0]){
                return a[1] - b[1];
         }
         return a[0] - b[0];
  });

//here 'arr' is an n*2 array

Sorting based on column1 (descending)

Arrays.sort(arr, (a,b)-> {
            if(b[0] == a[0]){
                return b[1] - a[1];
         }
         return b[0] - a[0];
  });

Sorting based on column2 (ascending)

 Arrays.sort(arr, (a,b)-> {
            if(a[1] == b[1]){
                return a[0] - b[0];
         }
         return a[1] - b[1];
  });

Sorting based on column2 (descending)

Arrays.sort(arr, (a,b)-> {
            if(b[1] == a[1]){
                return b[0] - a[0];
         }
         return b[1] - a[1];
  });

Upvotes: 2

BlueJapan
BlueJapan

Reputation: 1746

In java 8, you can use

Arrays.sort(array, (a,b) -> (b[0],a[0])); // in a descending order

Upvotes: 0

Duy Tran
Duy Tran

Reputation: 141

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

Upvotes: 5

Related Questions