#having a hard time understanding why my comparator logic on 2D array is wrong

1 messages · Page 1 of 1 (latest)

astral rapids
#

I have a 2D array where each array contains two elements i.e. int[n][2]

i want to sort the array (ascending order) such that the 1th index value of element A will be less than 0th index value of element B.

so i tried below comparator

import java.io.*;
import java.util.*;

class HelloWorld {
    public static void main(String[] args) {
        int[][] pairs = new int[][] {{3, 4}, {2, 3}, {1, 2}};
        
        Arrays.sort(pairs, (a, b) -> Integer.compare(a[1], b[0]));
        
        for (int[] pair : pairs) {
            System.out.println(Arrays.toString(pair));
        }
    }
}

but the ordering is unaffected.

however, the below comparator returns my expected output when i compare the 1th indexes of both A and B

(a, b) -> Integer.compare(a[1], b[1]).

i don't get why my logic is wrong. help is appreciated.

slim relicBOT
#

<@&987246399047479336> please have a look, thanks.

halcyon wren
#

You can tweak your comparator to yield some debugging...

Arrays.sort(pairs, (a, b) -> {
    int c = Integer.compare(a[1], b[0]);
    System.out.println("Comparing: " + Arrays.toString(a) + " -> " + Arrays.toString(b) + " = " + c);
    return c;
});

Keeping in mind that it's comparing the 2nd value of a to the first value of b in each comparison.

vernal quail