Reputation: 45
Suppose I have an array test-
int[] test={5,4,3,2,1};
Now when I sort this array in increasing order I want to store the indices of the elements in a new array. So sorting the above array in increasing order should create a new array with values {4,3,2,1,0} In C++ this is the code--
vector<int> order(n);
iota(order.begin(),order.end(),0);
sort(order.begin(),order.end(),[&](int i,int j){
return test[i]<=test[j];
});
I wanted to know how I can implement this in Java using the comparator class
Upvotes: 0
Views: 69
Reputation: 18450
You can sort all the index by that index's value using Comparator.comparing
this way
int[] res = IntStream.range(0, test.length)
.boxed()
.sorted(Comparator.comparing(e -> test[e]))
.mapToInt(e -> e)
.toArray();
Output: [4, 3, 2, 1, 0]
Upvotes: 1