1

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

2 Answers 2

1

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

Integer numOfKeys1 = int1[0];
Integer numOfKeys2 = int2[0];
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.