Permute the elements of an array
PermutationArray1.javastatic void applyPermutation1(int[] perm, int[] A) {
for (int i = 0; i < A.length; ++i) {
if (perm[i] >= 0) {
int a = i;
int temp = A[i];
do {
int nextA = perm[a];
int nextTemp = A[nextA];
A[nextA] = temp;
// Mark a as visited by using the sign bit.
perm[a] -= perm.length;
a = nextA;
temp = nextTemp;
} while (a != i);
}
}
// Restore perm back.
int size = perm.length;
for (int i = 0; i < perm.length; i++) {
perm[i] += size;
}
}
PermutationArray2.java
static void applyPermutation2(int[] perm, int[] A) {
for (int i = 0; i < A.length; ++i) {
// Traverse the cycle to see if i is the min element.
boolean isMin = true;
int j = perm[i];
while (j != i) {
if (j < i) {
isMin = false;
break;
}
j = perm[j];
}
if (isMin) {
int a = i;
int temp = A[i];
do {
int nextA = perm[a];
int nextTemp = A[nextA];
A[nextA] = temp;
a = nextA;
temp = nextTemp;
} while (a != i);
}
}
}