我想在 Java 中构建一个方法,用于根据多个给定列中的值对数组进行排序。让我用一个例子(矩阵数组)来解释一下:
int matrix[][] = {
{0,2,432},{1,1,282},{2,2,456},{3,4,191},{4,5,293},
{5,2,475},{6,2,491},{7,5,171},{8,5,134},{9,3,354}};
我需要根据第二个位置以降序对每个三元组进行排序。之后,我需要根据第三个位置对三元组进行升序排序。
我使用的代码是:
import java.util.*;
public class sort2DMatrixByColumn {
// Function to sort by column
public static void sortByColumn(int arr[][], int col) {
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] < entry2[col])
return 1;
else
return -1;
}
}); // End of function call sort().
}
// Driver Code
public static void main(String args[]) {
int matrix[][] = {
{0,2,432},{1,1,282},{2,2,456},{3,4,191},{4,5,293},
{5,2,475},{6,2,491},{7,5,171},{8,5,134},{9,3,354}};
// Sort this matrix by 2rd Column
int col = 2;
sortByColumn(matrix, col - 1);
// Display the sorted Matrix
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
}
前面描述的代码的输出是:
[[8,5,134],[7,5,171],[4,5,293],[3,4,191],[9,3,354],
[6,2,491],[5,2,475],[2,2,456],[0,2,432],[1,1,282]]
但是需要的输出必须是:
[[8,5,134],[7,5,171],[4,5,293],[3,4,191],[9,3,354],
[0,2,432],[2,2,456],[5,2,475],[6,2,491],[1,1,282]]
请注意,根据第二个位置,我们有以下顺序:5,5,5,4,3,2,2,2,2,1(递减顺序),根据第三个位置,顺序为:134,171,293 (对于第二个位置有“5”的三元组)、191(对于第二个位置有“4”的三元组)、354(对于第二个位置有“3”的三元组)、432,456,475,491(对于第二个位置有“3”的三元组)第二个位置有“2”的三元组),最后第二个位置有“1”的三元组是 282。
任何帮助将不胜感激。谢谢。
最佳答案
从 sortByColumn 方法中删除 col 参数,因为它实际上不是一个参数,并按以下方式更改该方法:
// Function to sort by column
public static void sortbyColumn(int arr[][]) {
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1, final int[] entry2) {
if (entry1[1] < entry2[1])
return 1;
else if (entry1[1] > entry2[1])
return -1;
return -1 * Integer.valueOf(entry2[2])
.compareTo(Integer.valueOf(entry1[2]));
}
}); // End of function call sort().
}
当然将 main 中的调用更改为 sortbyColumn(matrix);
说明:
只有在第二列相等的情况下才需要按第三列进行比较(这意味着第一次比较数值结果等于 0)。在这种情况下,我们以相反的顺序进行比较,将比较结果乘以 -1
即可获得。
结果:
8 5 134
7 5 171
4 5 293
3 4 191
9 3 354
0 2 432
2 2 456
5 2 475
6 2 491
1 1 282
关于java - 按多列中的值对二维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60689084/