<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
<head>
<meta http-equiv=
"Content-Type"
content=
"text/html; charset=utf-8"
/>
<title>JavaScript shuffle數組洗牌</title>
<body>
<script>
function
createArray(max) {
const arr = [];
for
(let i = 0; i < max; i++) {
arr.push(i);
}
return
arr;
}
function
shuffleSort(arr) {
arr.sort(()=> {
//返回值大於0,表示需要交換;小於等於0表示不需要交換
return
Math.random() > .5 ? -1 : 1;
});
return
arr;
}
function
shuffleSwap(arr) {
if
(arr.length == 1)
return
arr;
//正向思路
// for(let i = 0, n = arr.length; i < arr.length - 1; i++, n--) {
// let j = i + Math.floor(Math.random() * n);
//逆向思路
let i = arr.length;
while
(--i > 1) {
//Math.floor 和 parseInt 和 >>>0 和 ~~ 效果一樣都是取整
let j = Math.floor(Math.random() * (i+1));
/*
//原始寫法
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
*/
//es6的寫法
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return
arr;
}
function
wrap(fn, max) {
const startTime =
new
Date().getTime();
const arr = createArray(max);
const result = fn(arr);
const endTime =
new
Date().getTime();
const cost = endTime - startTime;
console.log(arr);
console.log(
"cost : "
+ cost);
}
wrap(shuffleSort, 1000);
wrap(shuffleSwap, 1000);
//試驗證明這種方法比第一種效率高多了
</script>
</body>
</html>
|
這里使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼,可得如下運行結果:

