How to find the permutation of a sort in Java

后端 未结 5 1034
攒了一身酷
攒了一身酷 2021-01-11 22:41

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

5条回答
  •  清酒与你
    2021-01-11 23:20

    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();
    }
    

提交回复
热议问题