尝试对
(value, index)按值比较的对进行排序:
public class Pair implements Comparable<Pair> { public final int index; public final int value; public Pair(int index, int value) { this.index = index; this.value = value; } @Override public int compareTo(Pair other) { //multiplied to -1 as the author need descending sort order return -1 * Integer.valueOf(this.value).compareTo(other.value); }}然后,当您要排序时:
public static void main(String[] args) { Pair[] yourArray = new Pair[10]; //fill the array yourArray[0] = new Pair(0, 5); yourArray[1] = new Pair(1, 10); //and so on Arrays.sort(yourArray);}现在,您具有
Pair按
value降序排列的对象数组。每个对象还包含
index-原始数组中的位置。
PS:我用Java编写了示例,因为问题带有
java标签。尽管在
C++思想上是相同的,但是只有实现有所不同。



