前面已经总结了几种常见的数组排序方法:冒泡排序,选择排序等等。
今天总结一下随机排序,每执行一次函数,对数组进行一次随机性的排序:

代码如下:
/**
* 随机算法
* @param {*} array
*/
import {
swap
} from "../utils/index.js"
function shuffle(array) {
for (let index = 0; index < array.length; index++) {
const randomIndex = Math.floor(Math.random() * (index + 1))
swap(array, index, randomIndex)
}
return array;
}
console.log(shuffle([2,354,4,6.5,8]))
function swap(arr, a,) {
[arr[a], arr[b]] = [arr[b], arr[a]]
}