【问题标题】:How do I sort a 2D array to ascending order? [closed]如何按升序对二维数组进行排序? [关闭]
【发布时间】:2021-04-11 06:57:14
【问题描述】:

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

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

我想要这样的东西:

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

【问题讨论】:

  • 你能编辑你的帖子吗?目前尚不清楚您的 2D 阵列的布局是什么。另外,请尝试更详细地解释您的问题。
  • 欢迎来到 StackOverflow,这个社区不是免费的编码服务。请展示您尝试解决任务并解决特定问题的实际尝试,并且肯定有人会尽快给予答复
  • 首先喜欢所有偶数然后是奇数?
  • 如果是,您最后输入的内容将被切换

标签: java arrays sorting multidimensional-array


【解决方案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;
        }
    }
}

【讨论】:

  • 除非我弄错了,如果你用 int[] temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; 替换掉你的交换,它会更干净一点。这只是交换实际的一维数组而不是创建一个新数组。但无论如何,原始作品如此+1。
【解决方案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));

【讨论】:

  • 或者不创建新数组Arrays.sort(array, Comparator.comparingInt( (int[] row) -&gt; row[0] ).thenComparingInt( (int[] row) -&gt; row[1]) );.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 2014-11-18
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多