如何将二维数组按升序排序?

时间:2021-01-05 14:02:16

标签: java arrays sorting multidimensional-array

我有一个像这样的二维数组:

[0] [4]
[1] [3]
[0] [7]
[7] [8]
[1] [2]
[7] [3]

我想要这样的东西:

[0] [4]
[0] [7]
[1] [2]
[1] [3]
[7] [3]
[7] [8]

2 个答案:

答案 0 :(得分:2)

使用比较器比较第一个单元格,如果相等,则比较第二个单元格。流式传输 2D 数组时,结果是 1D 数组的流(在这种情况下,长度为 2)。然后使用比较器对它们进行排序,然后作为 2D 数组返回。

int[][] array = {{0, 4}, {1, 3}, {0, 7}, {7, 8}, {1, 2}, {7, 3}};

Comparator<int[]> first = Comparator.comparingInt(a -> a[0]);
Comparator<int[]> second = Comparator.comparingInt(a -> a[1]);
array = Arrays.stream(array)
        .sorted(first.thenComparing(second))
        .toArray(int[][]::new);

for (int[] a : array) {
    System.out.println(Arrays.toString(a));
}

印刷品

[0, 4]
[0, 7]
[1, 2]
[1, 3]
[7, 3]
[7, 8]

这是一种使用选择排序的非流方法。但是对于大型数据集效率不高。

for (int i = 0; i < array.length - 1; i++) {
    for (int k = i + 1; k < array.length; k++) {
        // sort in ascending order on the first cells and then
        // if equal, on the second cells
        if (array[k][0] > array[i][0]
                || array[k][0] == array[i][0]
                && array[k][1] > array[i][1]) {

            // simply swap each 1D array
            int[] temp = array[i];
            array[i] = array[k];
            array[k] = temp;
        }
    }
}

或者如 Pshemo 善意建议,使用上述比较器。这会在不创建新数组的情况下进行就地排序。

Arrays.sort(array, first.thenComparing(second));

答案 1 :(得分:1)

这将获取数组 a 并按列 0 对其进行排序。如果 cumlumn 0 具有相同的数字,它将查看列 1 进行排序。

int[][] a = {{0, 4}, {1, 3}, {0, 7}, {7, 8}, {1, 2}, {7, 3}};

for (int i = 0; i < a.length - 1; i++) {
    if (a[i][0] > a[i + 1][0]) {
        int[][] temp = {{a[i + 1][0], a[i + 1][1]}};
        a[i + 1][0] = a[i][0];
        a[i + 1][1] = a[i][1];
        a[i][0] = temp[0][0];
        a[i][1] = temp[0][1];
        i = 0;
    } else if (a[i][0] == a[i + 1][0]) {
        if (a[i][1] > a[i + 1][1]) {
            int[][] temp = {{a[i + 1][0], a[i + 1][1]}};
            a[i + 1][0] = a[i][0];
            a[i + 1][1] = a[i][1];
            a[i][0] = temp[0][0];
            a[i][1] = temp[0][1];
            i = 0;
        }
    }
}
相关问题