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 ge
As an update, this is relatively easy to do in Java 8 using the streams API.
public static int[] sortedPermutation(final int[] items) {
return IntStream.range(0, items.length)
.mapToObj(value -> Integer.valueOf(value))
.sorted((i1, i2) -> Integer.compare(items[i1], items[i2]))
.mapToInt(value -> value.intValue())
.toArray();
}
It somewhat unfortunately requires a boxing and unboxing step for the indices, as there is no .sorted(IntComparator)
method on IntStream
, or even an IntComparator
functional interface for that matter.
To generalize to a List
of Comparable
objects is pretty straightforward:
public static > int[] sortedPermutation(final List items) {
return IntStream.range(0, items.size())
.mapToObj(value -> Integer.valueOf(value))
.sorted((i1, i2) -> items.get(i1).compareTo(items.get(i2)))
.mapToInt(value -> value.intValue())
.toArray();
}