Idea
Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.
思路
- 设置固定空桶数
- 将数据放到对应的空桶中
- 将每个不为空的桶进行排序
- 拼接不为空的桶中的数据,得到结果
步骤演示
假设一组数据(长度为 20)为
[63,157,189,51,101,47,141,121,157,156,194,117,98,139,67,133,181,13,28,109]
现在需要按 5 个分桶,进行桶排序,实现步骤如下:
- 找到数组中的最大值 194 和最小值 13,然后根据桶数为 5,计算出每个桶中的数据范围为
(194-13+1)/5=36.4
;
- 遍历原始数据,以第一个数据 63 为例,先找到该数据对应的桶序列(
Math.floor(63 - 13) / 36.4) =1
),然后将该数据放入序列为 1 的桶中(从 0 开始算);
- 当向同一个桶中第二次插入数据时,判断桶中已存在的数字与新插入的数字的大小,按从左到右,从小打大的顺序插入。如第一个桶已经有了 63,再插入 51,67 后,桶中的排序为 (51,63,67) ,一般通过链表来存放桶中数据。
- 全部数据装桶完毕后,按序列,从小到大合并所有非空的桶(0,1,2,3,4 桶)
- 合并完之后就是排序好的数据了
...