I have a 2d array called interval[g][2] where g is some number. Currently, I'm trying to sort the array first by increasing order in the first element, and if they are equal, sort by decreasing order in the second element.
I've attempted this in two ways:
1) Using Java 8's Comparator.comparing method:
Arrays.sort(interval, Comparator.comparing((int[] arr) -> arr[0]));
2) Using Arrays.sort:
Arrays.sort(interval, new Comparator<int[]>() {
@Override
public int compare(int[] s1, int[] s2) {
if (s1[0] > s2[0])
return 1;
else if (s1[0] < s2[0])
return -1;
else {
if(s1[1] < s2[1])
return 1;
else if (s1[1] > s2[1])
return -1;
else
return 0;
}
}
});
The first method returns a partially sorted list.
[[0, 10], [10, 30], [30, 50]]
[[0, 10], [3, 19], [35, 45]]
[[10, 30], [27, 33], [30, 50]]
[[-10, 10], [0, 20], [35, 45]]
[[10, 30], [20, 40], [30, 50]]
[[0, 20], [8, 28], [37, 43]]
[[0, 20], [15, 35], [37, 43]]
[[0, 0], [8, 28], [10, 40]]
As you can see, it's sorting things in a set of three tuples.
The second method doesn't sort the array at all. Can I not sort using primitive data types? Can anyone advise?