Hello,
I think I found much simpler solution than presented in the book to problem 6.13. What do you think?
(For clarity, checks for valid input are omitted).
Given an array A of n elements and a permutation P, apply P to A using only constant additional storage. Use A itself to store the result.
public static int[] permuteArray(int[] a, int[] p) {
int permIdx = 0;
int toBeReplaced;
int replacement = a[0];
#
for (int i = 0; i < a.length; i++) {
toBeReplaced = a[p[permIdx]];
a[p[permIdx]] = replacement;
permIdx = p[permIdx];
replacement = toBeReplaced;
}
#
return Arrays.copyOf(a, a.length);
}
(Couldn’t figure out how to enter a line break, so I used a dummy ‘#’ character).
Thanks,
Lukasz