繁体   English   中英

按列中的值对二维整数数组进行排序

[英]Sorting a 2D array of integers by values in columns

我正在尝试根据每列的值按递增顺序对 Java 中的2D array整数2D array进行排序。

让我用下面的例子来解释我的目标:

这是我的数组

int[][] array = new int[][]{
        {7, 3, 9},
        {9, 1, 3},
        {5, 8, 8}};

这是预期的数组

int[][] newArray = new int[][]{
        {5, 1, 3},
        {7, 3, 8},
        {9, 8, 9}};

从示例中可以看出, newArray上的每个值都与array相同,但现在在每列中按递增顺序排列。

论坛里几乎所有的问题都集中在如何根据行或列的值对二维数组进行排序,但我对每一列都需要这个。

你可以这样做。

  • 静态 Lambda 按列进行排序。 我这样做是为了绕过修改流内部局部变量的有效最终限制,在这种情况下是列。
  • sortByColumn方法为每个列数调用此 lambda。
  • 这只支持矩形矩阵。
static BiFunction<int[][], Integer, int[][]> sortColumn = (arr,c) -> {
     int[] temp = IntStream.range(0, arr.length)
        .map(i -> arr[i][c]).sorted().toArray();
     for (int i = 0; i < arr.length; i++) {
         arr[i][c] = temp[i];
     }
     return arr;
};
    
public static void main(String[] args) {
    int[][] array =
            new int[][] { { 7, 3, 9 }, { 9, 1, 3 }, { 5, 8, 8 } };
    
    array = sortByColumn(array);
    System.out.println(Arrays.deepToString(array)); 
}

印刷

[[5, 1, 3], [7, 3, 8], [9, 8, 9]]
    
public static int[][] sortByColumn(int[][] arr) {
     for (int col = 0; col < arr[0].length; col++) {
         arr = sortColumn.apply(arr,col);
     }
     return arr;
}

要对矩阵的列的元素进行排序,您可以对转置矩阵的行的元素进行排序,然后将其转回:

int m = 3;
int n = 4;
int[][] arr = {
        {7, 3, 9, 2},
        {9, 1, 3, 1},
        {5, 8, 8, 7}};
// sorting transposed matrix
int[][] arr2 = IntStream
        // iterate over the indices
        // of the rows of the matrix
        .range(0, n)
        .mapToObj(i -> IntStream
                // iterate over the
                // indices of the columns
                .range(0, m)
                .map(j -> arr[j][i])
                .sorted()
                .toArray())
        .toArray(int[][]::new);
// transposing sorted matrix
int[][] arr3 = IntStream
        // iterate over the indices of the
        // rows of the transposed matrix
        .range(0, m)
        .mapToObj(i -> IntStream
                // iterate over the
                // indices of the columns
                .range(0, n)
                .map(j -> arr2[j][i])
                .toArray())
        .toArray(int[][]::new);
// output
Arrays.stream(arr3).map(Arrays::toString).forEach(System.out::println);
[5, 1, 3, 1]
[7, 3, 8, 2]
[9, 8, 9, 7]

另请参阅:按列对二维整数数组进行排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM