Last active
December 23, 2015 11:29
-
-
Save hxlniada/6628163 to your computer and use it in GitHub Desktop.
数组全排序
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
/******************* | |
* javascript | |
*第一种方式实现全排序 | |
******************* | |
*/ | |
var result = []; | |
function permutation1(arr) { | |
perm1(arr, 0); | |
document.write(result.join('<br />')); | |
} | |
function perm1(arr, index) { | |
var n = arr.length, | |
j; | |
if (index === n - 1) { | |
result.push(arr.slice()); | |
return false; | |
} else { | |
for (j = index; j < n; ++j) { | |
swap(arr, j, index); | |
arguments.callee(arr, j + 1); | |
swap(arr, j, index); | |
} | |
} | |
} | |
function swap(arr, index1, index2) { | |
var temp = arr[index1]; | |
arr[index1] = arr[index2]; | |
arr[index2] = temp; | |
} | |
/************************* | |
* javascript | |
* 第二种方式实现全排序 | |
* ********************** | |
*/ | |
var result = [], | |
temp = []; | |
function permutation2(arr) { | |
var n = arr.length, | |
i; | |
for (i = 0; i < n; ++i) { | |
temp[i] = 0; | |
} | |
perm2(arr, n - 1); | |
document.write(result.join('<br />')); | |
} | |
function perm2(arr, index) { | |
var n = arr.length; | |
i; | |
if (index === 0) { | |
result.push(temp.slice()); | |
return false; | |
} else { | |
for (i = 0; i < n; ++i) { | |
if (temp[i] === 0) { | |
temp[i] = arr[index]; | |
auguments.callee(arr, index - 1); | |
temp[i] = 0; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment