It was the smallest numbers but I lost indexes of this values, which they had i non-sorted array
Then why don't you just create a class to hold this indexes ? Then just sort your array by value and you'll get the index associated.
class MyClass implements Comparable<MyClass>{
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));
}
Note :
If you want to sort objects that have the same value by indexes, you can modify your comparator like this :
@Override
public int compareTo(MyClass m) {
int compareValue = value - m.value;
if(compareValue == 0)
return index - m.index;
return compareValue;
}
Output (with the second
compareTo
method) :
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]