js实现乱序
数组乱序的实现方法
使用 Fisher-Yates 算法可以高效地实现数组乱序。该算法通过遍历数组并随机交换元素位置来实现乱序。

function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
使用 sort 方法的简化实现
通过比较随机数来实现数组排序,这种方法代码简洁但效率较低。

function shuffleSort(array) {
return array.sort(() => Math.random() - 0.5);
}
生成随机索引的乱序方法
创建一个新数组,从原数组中随机选取元素放入新数组。
function randomIndexShuffle(array) {
const shuffled = [];
const copy = [...array];
while (copy.length > 0) {
const randomIndex = Math.floor(Math.random() * copy.length);
shuffled.push(copy.splice(randomIndex, 1)[0]);
}
return shuffled;
}
性能考虑
Fisher-Yates 算法的时间复杂度为 O(n),是最优的乱序算法。sort 方法的时间复杂度为 O(n log n),适合小型数组。随机索引方法需要额外的空间复杂度。
应用场景
Fisher-Yates 适用于大型数据集的乱序需求。sort 方法适合快速实现小型数组乱序。随机索引方法在需要保留原数组时适用。






