您可以使用自定义Comparator
比较各个索引处的等级数组中的值,
import java.util.*;
public class GradeComparator implements Comparator<Integer> {
private double[] grades;
public GradeComparator(double[] arr) {
grades = arr;
}
public int compare(Integer i, Integer j) {
return Double.compare(grades[j], grades[i]);
}
}
并使用它对索引数组进行排序Comaprator
:
导入 java.util.*;
public class SortGrades {
public static void main(String[] args) {
double[] grades = { 2.4, 6.1, 3.9, 4.8, 5.5 };
Integer[] ranks = new Integer[grades.length];
for(int i = 0; i < ranks.length; ++i) {
ranks[i] = i;
}
Comparator<Integer> gc = new GradeComparator(grades);
Arrays.sort(ranks, gc);
for(int i = 0; i < ranks.length; ++i) {
System.out.println((i+1) + ": " + ranks[i] + ", grade: " + grades[ranks[i]]);
}
}
}
输出
1: 1, grade: 6.1
2: 4, grade: 5.5
3: 3, grade: 4.8
4: 2, grade: 3.9
5: 0, grade: 2.4
如预期的。