Come aggiornamento, questo è relativamente facile da eseguire in Java 8 utilizzando l'API di streaming.
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();
}
È piuttosto richiede purtroppo boxe e passo unboxing per gli indici, in quanto non v'è alcun metodo .sorted(IntComparator)
su IntStream
, o anche un'interfaccia funzionale IntComparator
per quella materia.
generalizzare ad un List
di Comparable
oggetti è abbastanza semplice:
public static <K extends Comparable <? super K>> int[] sortedPermutation(final List<K> 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();
}
Guava-er molto cool! –
Mi sono trattenuto dall'usare Guava lì, ti farò sapere;) –