6分钟学会桶排序算法!
首先随机生成一个长度为5的乱序数组,且每个元素的数值大小是[0-9]
let numList = Array.from({ length: 5 }, (item) => {
// 每个元素都是0-9的随机数
return Math.floor(Math.random() * 10);
});
console.log("排序前数组:", numList);
因为前面限定随机数在0-9之间,所以我们创建一个长度为10的数组,也就是我们的桶,它用于统计乱序数组中每个元素出现的次数(没听懂?不要紧继续往下看)
我们把桶数组中每个元素初始值都设置为0
let censusList = Array.from({ length: 10 }, _ => 0);
我们遍历随机数组numList,出现的元素我们在censusList中给他+1
numList.map((item) => {
censusList[item]++;
});
假设numList是这样:
| key | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| value | 5 | 1 | 6 | 0 | 6 |
那么censusList应该是这样:
| key | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| value | 1 | 1 | 0 | 0 | 0 | 1 | 2 | 0 | 0 | 0 | 0 |
其中6在numList出现两次,那么censusList中下标6的数值为2
此时我们已经得到了乱序数组numList中每个元素出现的次数且按升序排序
我们把以上数组转为排序后的数组,如下:
let resList = censusList.map((item, index) => {
if(item == 1) {
return index;
} else if(item > 1) {
return Array.from({ length: item }, _ => index);
}
return undefined;
}).filter(_ => _ !== undefined).flat();
console.log("排序后数组:", resList);
你学费了吗