0

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

1
  • You should use ArrayList instead Vector, which as I understand has been deprecated for many years. Commented Sep 30, 2020 at 17:45

1 Answer 1

1

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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.