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?
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With