【发布时间】:2021-08-06 01:04:46
【问题描述】:
我正在尝试在 Java 中按行对二维数组进行排序。但是,我只想对索引进行排序,而不是对值本身进行排序。
例如:
values
1.3 0.3 0.4 0.1
0.4 0.2 3.7 2.4
2.1 6.4 1.9 0.3
indices sorted according to values
0 1 2 3 3 1 2 0
0 1 2 3 --> 1 0 3 2
0 1 2 3 3 2 0 1
不幸的是,我在其他 StackOverflow 问题中可以找到的任何内容要么是如何对矩阵进行排序,要么是在对数组进行排序时如何保留索引。但有效地结合两者是我努力的方向。
任何见解都将不胜感激。
到目前为止,我尝试了什么,但这不起作用。它似乎根本没有改变我的矩阵。
// Function to sort the given matrix in row wise manner
public void RowWiseSort(Integer[][] idx, double[][] values) {
// Traverse the row
for (int i = 0; i < (int) idx.length; i++) {
ArrayIndexComparator comp = new ArrayIndexComparator(values[i]);
// Row - Wise Sorting
Arrays.sort(idx[i], comp);
}
}
private class ArrayIndexComparator implements Comparator<Integer> {
private final double[] A;
public ArrayIndexComparator(double[] arr) {
this.A = arr;
}
@Override
public int compare(Integer o1, Integer o2) {
return Double.compare(A[o1], A[o2]);
}
}
【问题讨论】:
标签: java arrays sorting matrix multidimensional-array