Renuka
Renuka

Reputation: 21

Arrays.sort for 2-D Integer Array failing

I'm using the below method to sort a 2D Integer array. But there seems to be some issue with the sorting. Can someone please help.

private static Integer[][] sort(Integer[][] bs) {

    Arrays.sort(bs, new Comparator<Integer[]>() {
        @Override
        public int compare(Integer[] int1, Integer[] int2) {
            Integer numOfKeys1 = int1[1];
            Integer numOfKeys2 = int2[1];
            return numOfKeys1.compareTo(numOfKeys2);
        }
    });

    return bs;
  }

Input Array:

480 615
1320 1395
1020 1140
420 585
540 780
960 1065
720 810
690 750

Output:

420 585
480 615
690 750
540 780 - not sorted
720 810
960 1065
1020 1140
1320 1395

Upvotes: 1

Views: 80

Answers (2)

Danstahr
Danstahr

Reputation: 4319

It actually IS sorted, but the key is the second record in your array. To sort it by the first node, you need to change your comparator to

public int compare(Integer[] int1, Integer[] int2) {
    Integer numOfKeys1 = int1[0];
    Integer numOfKeys2 = int2[0];
    return numOfKeys1.compareTo(numOfKeys2);
}

Or better write a comparator that sorts lexicographically

public int compare(Integer[] int1, Integer[] int2) {            
    int minlen = Math.min(int1.length, int2.length);
    for (int i = 0; i < minlen; ++i) {
        int cmp = int1[i].compareTo(int2[i]);
        if (cmp != 0) {
            return cmp;
        }
    }
    // so far the arrays are same, the shorter goes first
    return int1.length - int2.length;
}

Upvotes: 1

OnABauer
OnABauer

Reputation: 599

You're sorting by the second value not the first. Try something like:

Integer numOfKeys1 = int1[0];
Integer numOfKeys2 = int2[0];

Upvotes: 1

Related Questions