我有一个数组
double[] weights = { 32.0, 32.0, 25.0, 25.0, 30.0, 28.0,
12.0, 10.0, 8.0, 8.0, 18.0, 0.0 };
我想根据 weights
的降序排序其对应的索引 0
到 11
:
{ 32.0, 32.0, 30.0, 28.0, 25.0, 25.0, 18.0, 12.0, 10.0, 8.0, 8.0, 0.0 }
在这种情况下,我想要的输出是 int[]
:
{ 0, 1, 4, 5, 2, 3, 10, 6, 7, 8, 9, 11 }
我添加了一个 int[] 值来跟踪索引:
int[] values = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }
最佳答案
做一个类似的容器类,像这样
class EvanContainer implements Comparable<EvanContainer> {
double weight;
int value;
EvanContainer(double w, int v) { weight = w; value = v; }
public int compareTo(EvanContainer other) {
return Double.compare(weight, other.weight);
}
}
然后你可以正常排序。
EvanContainer[] container = new EvanContainer[weights.length];
for(int i = 0; i < weights.length; i++) {
container[i] = new EvanContainer(weights[i],values[i]);
}
Arrays.sort(container);
关于java - 通过 double[] 数组对 int[] 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8378831/