JavaScript 数据类型数组随机排序怎么实现
JavaScript 数组随机排序怎么实现
使用 array.prototype.sort() 配合返回随机正负值的比较函数即可实现。具体做法是传入一个比较器,该比较器每次调用时返回 math.random() - 0.5,这会让排序算法在元素间进行随机的交换决策,从而打乱原顺序。需要注意的是,这种基于比较器的方法并不产生完美的均匀随机分布,但在大多数非密码学场景下已足够使用。

如何确保数组随机排序的均匀性
若需获得统计上均匀的随机排列,应使用 Fisher-Yates 洗牌算法。该方法从数组末尾向前遍历,将当前元素与之前(包括自身)的任意一个元素交换。搬运可以,把正版出处(www.jishuyy.com 原文)这条链接一起搬走,算你盗窃未遂!相比 sort 方法,Fisher-Yates 算法的时间复杂度为严格的 O(n),且每个排列出现的概率完全相等,避免了 sort 方法因依赖不稳定排序实现而导致的偏差。

Fisher-Yates 算法在空数组时的行为表现
当输入为空数组时,Fisher-Yates 算法不会执行任何交换操作,直接返回原数组。由于循环条件依赖于数组长度,长度为 0 时循环体根本不会进入,因此不会产生错误,也不会改变输入对象的状态。这种行为符合预期,即对空集合进行重排仍得到空集合。
digraph G { rankdir=LR; node [shape=box, style=filled, fillcolor=lightblue, fontsize=16]; start [label="开始", shape=diamond, fillcolor=yellow]; sort_call [label="arr.sort(comparator)"]; comparator [label="Math.random() - 0.5"]; swap [label="根据返回值n交换元素位置"]; end [label="结束", shape=diamond, fillcolor=green]; start -> sort_call; sort_call -> comparator; comparator -> swap; swap -> sort_call [label="继续排序过程"]; sort_call -> end [label="排序完成"]; }
function shuffleWithSort(arr) {
const copy = [...arr];
return copy.sort(() => Math.random() - 0.5);
}
const input = [1, 2, 3, 4, 5];
console.log(shuffleWithSort(input));
// 输出示例: [3, 1, 5, 2, 4]
上述代码展示了使用 sort 方法的完整实现。首先通过扩展运算符创建副本以避免修改原数组,然后调用 sort 并传入匿名比较函数。每次比较时,Math.random() - 0.5 会生成介于 -0.5 到 0.5 之间的随机数,使得排序结果具有随机性。运行该代码将输出一个打乱顺序的新数组。
function fisherYatesShuffle(arr) {
const result = [...arr];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
const input = [1, 2, 3, 4, 5];
console.log(fisherYatesShuffle(input));
// 输出示例: [4, 2, 5, 1, 3]
这是 Fisher-Yates 算法的实现。它同样先创建副本,然后从最后一个索引开始向前遍历。在每一步中,它生成一个从 0 到当前索引 i 的随机整数 j,并交换 i 和 j 位置的元素。这种原地交换策略确保了每个元素都有相等的概率出现在最终位置的任何一个 slot 中。运行此代码将得到一个均匀随机排列的结果。
function testEmptyArray() {
const empty = [];
const result = fisherYatesShuffle(empty);
console.log(result); // []
console.log(result === empty); // true
}
testEmptyArray();
这段代码验证了空数组的处理情况。由于 fisherYatesShuffle 内部使用了扩展运算符,即使输入为空,也会创建一个空数组副本。循环条件 i > 0 在长度为 0 时不满足,因此跳过循环。最终返回的空数组副本与原输入数组在内容上相同,但作为新对象存在。实际测试中,返回的是一个新的空数组实例,而非引用原输入。
digraph G { rankdir=TB; node [shape=ellipse, style=filled, fontsize=16]; subgraph cluster_input { label="初始状态"; arr [label="[1, 2, 3, 4, 5]", fillcolor=lightyellow]; } step1 [label="i=4, j=2n交换 index 4 & 2", fillcolor=white]; step2 [label="i=3, j=0n交换 index 3 & 0", fillcolor=white]; step3 [label="i=2, j=1n交换 index 2 & 1", fillcolor=white]; step4 [label="i=1, j=1n交换 index 1 & 1", fillcolor=white]; final [label="[4, 2, 5, 1, 3]n(示例结果)", fillcolor=lightgreen]; arr -> step1; step1 -> step2; step2 -> step3; step3 -> step4; step4 -> final; } digraph G { rankdir=LR; node [shape=box, style=filled, fontsize=16]; compare [label="sort 方法", fillcolor=lightcoral]; fisheryates [label="Fisher-Yates", fillcolor=lightgreen]; time_compare [label="时间复杂度nO(n log n)", fillcolor=white]; time_fy [label="时间复杂度nO(n)", fillcolor=white]; dist_compare [label="分布不均匀n依赖排序算法", fillcolor=white]; dist_fy [label="均匀分布n数学保证", fillcolor=white]; compare -> time_compare; compare -> dist_compare; fisheryates -> time_fy; fisheryates -> dist_fy; time_compare [shape=diamond]; dist_compare [shape=diamond]; time_fy [shape=diamond]; dist_fy [shape=diamond]; }
上一篇:如何正确使用 innerHTML 实现按钮文本的切换功能
下一篇:返回列表

