Please I don't seem to know what is wrong with this my C# implementation of the heaps permutation algorithm. It does not give the correct permutation of an input array. Can somebody help me out?
Here is the pseudo-code
procedure generate(n : integer, A : array of any):
if n = 1 then
output(A)
else
for i := 0; i < n - 1; i += 1 do
generate(n - 1, A)
if n is even then
swap(A[i], A[n-1])
else
swap(A[0], A[n-1])
end if
end for
generate(n - 1, A)
end if
this is my c# Implementation
static void Permute(int[] A, int n) {
if (n == 1) {
printArray(A);
} else {
for (int i = 0; i < n - 1; i++) {
Permute(A, n - 1);
if (n % 2 == 0) {
A = Swap(A, A[i], A[n - 1]);
printArray(A);
} else {
A = Swap(A, A[0], A[n - 1]);
printArray(A);
}
}
Permute(A, n - 1);
}
}
static int[] Swap(int[] A, int x, int y) {
int temp;
temp = A[x];
A[x] = A[y];
A[y] = temp;
return A;
}
static void printArray(int[] A) {
foreach(var x in A) {
Console.Write(x);
}
Console.WriteLine();
}