Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 796
user491880 Avatar asked Aug 17 '12 00:08

user491880


People also ask

How do you find the permutation of an array in Java?

You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element.

How do you find the permutation of an array?

All permutations of an array using STL in C++ Approach: The next possible permutation of the array can be found using next_permutation() function provided in STL. Syntax: bool next_permutation (BidirectionalIterator first, BidirectionalIterator last);


1 Answers

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.

like image 55
Louis Wasserman Avatar answered Sep 25 '22 22:09

Louis Wasserman