Skip to content

Instantly share code, notes, and snippets.

@javm
Last active May 19, 2017 17:02
Show Gist options
  • Save javm/85aaeeb734e6ca125c758bec53e90efa to your computer and use it in GitHub Desktop.
Save javm/85aaeeb734e6ca125c758bec53e90efa to your computer and use it in GitHub Desktop.
Heap's algorithm to generate the permutation of an array of n elemets
function permutations(s, cb){
let n = s.length;
function swap(i, j){
let tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
function heapGenerate(n){
if(n === 1){
cb(s);
}else{
for(let i=0; i<n; i++){
heapGenerate(n-1);
if(n % 2 === 0){
swap(i,n-1);
}else{
swap(0,n-1);
}
}
}
}
heapGenerate(n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment