数据处理 | 数组乱序(shuffle)输出(3种)

灵魂拷问:数组乱序输出的方式你知道多少呢?

方式1:随机排序

随机抽取一个数,放进新数组中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 时间复杂度 O(n^2)
function randomSortArray(arr) {
let res = [];
while (arr.length) {
let index = parseInt(Math.random() * arr.length); // 可以在现有数组中随意抽取
res.push(arr[index]);
// 记得删除这个元素哦 不然会重复抽取
arr.splice(index, 1);
};
return res;
}


// test
const arr = [1,2,3,4,5,6,7,8,9]
console.log(randomSortArray(arr)) // [8, 4, 2, 9, 7, 6, 1, 3, 5] [温馨提示:结果勿轻信,每次都是随机的呀~]

方式2:sort

元素之间的位置交换取决于Math.random() - 0.5的结果是大于0 小于0 还是等于0

1
2
3
4
5
6
7
function randomSortArray(arr) {
return arr.sort(() => Math.random() - 0.5);
}

// test
const arr = [1,2,3,4,5,6,7,8,9]
console.log(randomSortArray(arr)) // [3, 6, 2, 9, 4, 8, 5, 7, 1] [温馨提示:结果勿轻信,每次都是随机的呀~]

方式3:洗牌法

将数组中的索引值随机打乱,交换当前索引值和随机变化后的索引值互换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 时间复杂度:O(n)
function randomSortArray(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
// randomIndex 处于 0 - arr.length之间,因为值不能是arr.length,所以Math.floor向下取值
let randomIndex = Math.floor(Math.random() * (i+1));
// 交换位置
[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
}
return arr;
}

// test
const arr = [1,2,3,4,5,6,7,8,9]
console.log(randomSortArray(arr)) // [4, 3, 5, 1, 8, 7, 6, 9, 2] [温馨提示:结果勿轻信,每次都是随机的呀~]