It was the smallest numbers but I lost indexes of this values, which
they had i non-sorted array
那你为什么不创建一个类来保存这个索引呢?
然后只需按值对数组进行排序,您就可以获得索引关联.
class MyClass implements Comparable{
private int index;
private int value;
public MyClass(int i, int v){
this.index = i;
this.value = v;
}
@Override
public String toString(){
return "Index: "+index+" Value: "+value;
}
@Override
public int compareTo(MyClass m) {
return value - m.value;
}
}
public static void main(String[] args){
MyClass[] array = new MyClass[20];
for(int i = 0; i < array.length; i++){
array[i] = new MyClass(i, someRandomValue); // Here I used (i*3 + 2)%5
}
System.out.println(Arrays.toString(array));
Arrays.sort(array);
MyClass [] arraySorted = Arrays.copyOfRange(array, 0, 10); //take the first ten elements
System.out.println(Arrays.toString(arraySorted));
}
注意 :
如果要按索引对具有相同值的对象进行排序,可以像这样修改比较器:
@Override
public int compareTo(MyClass m) {
int compareValue = value - m.value;
if(compareValue == 0)
return index - m.index;
return compareValue;
}
输出(使用第二个compareTo方法):
Before :
[Index: 0 Value: 2, Index: 1 Value: 0, Index: 2 Value: 3, Index: 3 Value: 1, Index: 4 Value: 4, Index: 5 Value: 2, Index: 6 Value: 0, Index: 7 Value: 3, Index: 8 Value: 1, Index: 9 Value: 4, Index: 10 Value: 2, Index: 11 Value: 0, Index: 12 Value: 3, Index: 13 Value: 1, Index: 14 Value: 4]
After :
[Index: 1 Value: 0, Index: 6 Value: 0, Index: 11 Value: 0, Index: 3 Value: 1, Index: 8 Value: 1, Index: 13 Value: 1, Index: 0 Value: 2, Index: 5 Value: 2, Index: 10 Value: 2, Index: 2 Value: 3]