桶排序

1. 基本原理

桶排序也叫箱排序。工作原理是将数组元素映射到有限数量个桶里,利用计数排序可以定位桶的边界,每个桶再各自进行桶内排序(使用其它排序算法或以递归方式继续使用桶排序)。

2. 算法步骤

  • 设置固定数量的空桶
  • 把数据放到对应的桶中
  • 对每个不为空的桶中数据进行排序
  • 拼接不为空的桶中数据,得到结果

3. 动画演示

桶排序 Bucket Sort

4. 参考实现

import Sort.internal.Comparison.InsertSort;

import java.util.Arrays;

/**
 * @author wylu
 */
public class BucketSort {

    //桶的个数
    private static int m = 5;

    //创建桶
    private static int[][] buildBucket(int[] arr, int min, int gap) {
        int[][] buckets = new int[m][];
        //每个桶的元素个数
        int[] counts = new int[m];
        for (int e : arr) counts[(e - min) / gap]++;
        for (int i = 0; i < m; i++) {
            buckets[i] = new int[counts[i]];
        }
        return buckets;
    }

    public static void sort(int[] arr) {
        int min = arr[0], max = arr[0];
        for (int e : arr) {
            if (e < min) min = e;
            if (e > max) max = e;
        }

        //桶的大小
        int gap = (max - min) / m + 1;
        int[][] buckets = buildBucket(arr, min, gap);

        //将每个元素映射到相应的桶中
        int[] cur = new int[m];
        for (int e : arr) {
            //桶编号
            int id = (e - min) / gap;
            buckets[id][cur[id]++] = e;
        }

        //进行桶内排序
        int idx = 0;
        for (int[] bucket : buckets) {
            if (bucket.length == 0) continue;
            InsertSort.sort(bucket);
            for (int e : bucket) {
                arr[idx++] = e;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {5, 3, 4, 7, 2, 4, 3, 4, 7};
        BucketSort.sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

5. 复杂度分析

排序算法 平均时间复杂度 最好情况 最坏情况 空间复杂度 排序方式 稳定性
桶排序 O(n+m)O(n + m) O(n+m)O(n + m) O(nlogn)O(n2)O(nlogn) \sim O(n^2) O(n+m)O(n+m) Out-place 稳定

6. References

图片来源
https://youliao.163yun.com/api-server/rss/xiaomi/item/IN2WDOMKAWVNTZV.html?ref=browser_news&s=mb&cp=cn-netease-youliao-browser&docid=44797c69e120935b2c4790d933d02a9b&itemtype=news&cateCode=rec&category=%E7%A7%91%E6%8A%80

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-12
  • 2022-12-23
  • 2021-08-30
  • 2021-09-04
  • 2021-07-15
猜你喜欢
  • 2021-04-05
  • 2021-06-05
  • 2021-06-14
  • 2021-12-14
  • 2022-02-28
  • 2021-11-07
  • 2022-02-02
相关资源
相似解决方案