I want to sort an array and find the index of each element in the sorted order. So for instance if I run this on the array:
[3,2,4]
I'd get:
[1,0,2]
Is there an easy way to do this in Java?
I want to sort an array and find the index of each element in the sorted order. So for instance if I run this on the array:
[3,2,4]
I'd get:
[1,0,2]
Is there an easy way to do this in Java?
Let's assume your elements are stored in an array.
Now
indices
contains the indices of the array, in their sorted order. You can convert that back to anint[]
with a straightforward enoughfor
loop.One way to achieve this is to make a list of pairs with the starting index as the second part of the pair. Sort the list of pairs lexicographically, then read off the starting positions from the sorted array.
Starting array:
Add pairs with starting indexes:
Sort it lexicographically
then read off the second part of each pair
As an update, this is relatively easy to do in Java 8 using the streams API.
It somewhat unfortunately requires a boxing and unboxing step for the indices, as there is no
.sorted(IntComparator)
method onIntStream
, or even anIntComparator
functional interface for that matter.To generalize to a
List
ofComparable
objects is pretty straightforward: