先按X,然后按Y对二维矩阵进行排序


int[][] points = new int[n][2];
..
//sort by x values and then y if x's are the same
Arrays.sort(points, (a, b) -> a[0] - b[0] == 0 ? a[1] - b[1] : a[0] - b[0]);

这是最佳解决方案吗?我刚刚在IDE中用一些随机数测试了它,它似乎有效。

与其他解决方案相比是最佳的?您正在对二维数组进行排序,并提供一个Comparator来控制排序。Arrays.sort实现了一种高效、稳定的排序算法。我会使用它,但我会指定比较器如下:

Arrays.sort(points, Comparator.comparingInt((int[] a) -> a[0])
.thenComparingInt(a -> a[1]));

根据比较器的要求减去元素不是一种好的做法,并且当值接近Integer.MAX_VALUEInteger.MIN_VALUE时,可能导致数据结构排序不正确。

您可以使用比较器链接,如下所示:

int[][] points;
// sorting the rows of a 2d array first by the
// first column and then by the second column
Arrays.sort(points, Comparator
.<int[], Integer>comparing(arr -> arr[0])
.thenComparing(arr -> arr[1]));

另请参阅:在Java中对2d数组进行排序

最新更新