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.