[英]Sorting a 2D array of integers by values in columns
I am trying to sort a 2D array
of integers in Java in increasing order according to the values of every column.我正在尝试根据每列的值按递增顺序对 Java 中的2D array
整数2D array
进行排序。
Let me explain my objective with the following example:让我用下面的例子来解释我的目标:
This is my array :这是我的数组:
int[][] array = new int[][]{
{7, 3, 9},
{9, 1, 3},
{5, 8, 8}};
Here is the expected array :这是预期的数组:
int[][] newArray = new int[][]{
{5, 1, 3},
{7, 3, 8},
{9, 8, 9}};
As can see in the example, every values on newArray
are the same as array
but now ordered in each column in increasing order.从示例中可以看出, newArray
上的每个值都与array
相同,但现在在每列中按递增顺序排列。
Almost all the questions in the forum are focused on how to sort a 2D array according to the values of a row or column, but I need this for every column.论坛里几乎所有的问题都集中在如何根据行或列的值对二维数组进行排序,但我对每一列都需要这个。
You could do it like this.你可以这样做。
sortByColumn
method calls this lambda for each number of columns. 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));
}
Prints印刷
[[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;
}
To sort the elements of the columns of a matrix, you can sort the elements of the rows of the transposed matrix and then transpose it back:要对矩阵的列的元素进行排序,您可以对转置矩阵的行的元素进行排序,然后将其转回:
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]
See also: Sorting 2D array of integers by column另请参阅:按列对二维整数数组进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.