Last active
May 19, 2017 17:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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