[英]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
相同,但現在在每列中按遞增順序排列。
論壇里幾乎所有的問題都集中在如何根據行或列的值對二維數組進行排序,但我對每一列都需要這個。
你可以這樣做。
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.