Search code examples
javaalgorithmsortingarray-algorithms

How to find the permutation of a sort 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?


Solution

  • Let's assume your elements are stored in an array.

    final int[] arr = // elements you want
    List<Integer> indices = new ArrayList<Integer>(arr.length);
    for (int i = 0; i < arr.length; i++) {
      indices.add(i);
    }
    Comparator<Integer> comparator = new Comparator<Integer>() {
      public int compare(Integer i, Integer j) {
        return Integer.compare(arr[i], arr[j]);
      }
    }
    Collections.sort(indices, comparator);
    

    Now indices contains the indices of the array, in their sorted order. You can convert that back to an int[] with a straightforward enough for loop.