I have been trying to understand Heap's Algorithm, for days, I still cannot wrap this in my head, something just feels wrong in this code of recursion within the loop. This is a Javascript version from recursion version in Heap's algorithm at Wikipedia.
function permAlone(string) {
var x = string.split(''); // Turns the input string into a letter array.
var arr = x; // this is global, I did this so i can see elements being swapped on swap function
function swap(a, b) { // This function will simply swap positions a and b inside the input array.
debugger;
var le = arr[a]; // element a
var lf = arr[b]; // element b
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
var yt = arr; // only did this to see updated elements on the array
}
var permutations = []; //output
function gen(length) {
if (length === 1) { // if true,
var x = arr.join('');
permutations.push(x); // push the updated joined' array
} else {
for (var i = 0; i < length; i++) { loop length = current elements
debugger;
gen(length - 1); // invoke recursion
swap(length % 2 ? 0 : i, length - 1); //invoke swap function. length % 2 ? 0 : i <- ternary test for the lengths' call stack. length -1 for the last element
}
}
}
gen(arr.length);
return permutations;
}
permAlone('abcd'); // this outputs to ["abcd", "bacd", "cabd", "acbd", "bcad", "cbad", "dbca", "bdca", "cdba", "dcba", "bcda", "cbda", "dacb", "adcb", "cdab", "dcab", "acdb", "cadb", "dabc", "adbc", "bdac", "dbac", "abdc", "badc"]
At first look on this code, I thought it was understandable, I understand it swaps the variable 'i'th value in the loop and the last element if it is even, then, If it's odd it swap the first and last value.. but when I saw the output, isn't the Recursion.. Recurring too much? Can someone please tell me why?