Java 桶排序

桶排序(Bucket Sort)是一种基于分布的排序算法,它的工作原理是将数组元素分散到有限数量的桶里,然后对每个桶分别进行排序(通常使用其他排序算法,如插入排序),最后依次合并各个桶中的元素,得到排序后的数组。桶排序适用于数据分布均匀的情况,其时间复杂度在最坏情况下是 O(n^2),但在数据均匀分布时,可以达到 O(n + k),其中 n 是数组的大小,k 是桶的数量。

以下是一个简单的 Java 实现桶排序的例子:

复制代码
import java.util.ArrayList;  
import java.util.Collections;  
  
public class BucketSort {  
  
    // 桶排序方法  
    public static void bucketSort(double[] array, int bucketSize) {  
        if (array.length == 0) {  
            return;  
        }  
  
        // 1. 创建桶  
        int bucketCount = (int) Math.floor((array[array.length - 1] - array[0]) / bucketSize) + 1;  
        ArrayList<ArrayList<Double>> buckets = new ArrayList<>(bucketCount);  
        for (int i = 0; i < bucketCount; i++) {  
            buckets.add(new ArrayList<>());  
        }  
  
        // 2. 将数组元素分配到各个桶中  
        for (double num : array) {  
            int bucketIndex = (int) Math.floor((num - array[0]) / bucketSize);  
            buckets.get(bucketIndex).add(num);  
        }  
  
        // 3. 对每个桶进行排序  
        int index = 0;  
        for (ArrayList<Double> bucket : buckets) {  
            Collections.sort(bucket);  
            for (double num : bucket) {  
                array[index++] = num;  
            }  
        }  
    }  
  
    // 测试桶排序  
    public static void main(String[] args) {  
        double[] array = {0.42, 0.32, 0.23, 0.52, 0.77, 0.36, 0.78, 0.31, 0.62, 0.16};  
        int bucketSize = 0.1;  
  
        System.out.println("排序前: ");  
        for (double num : array) {  
            System.out.print(num + " ");  
        }  
        System.out.println();  
  
        bucketSort(array, bucketSize);  
  
        System.out.println("排序后: ");  
        for (double num : array) {  
            System.out.print(num + " ");  
        }  
    }  
}

代码解释:

  1. 创建桶
    • 首先计算桶的数量,这里假设输入数组的元素在 [array[0], array[array.length - 1]] 范围内均匀分布。
    • 创建一个 ArrayListArrayList 来存储桶,每个桶也是一个 ArrayList
  2. 分配元素到桶中
    • 遍历数组中的每个元素,根据元素的值计算它应该属于哪个桶,并将其添加到相应的桶中。
  3. 对每个桶进行排序
    • 使用 Collections.sort 方法对每个桶进行排序。
    • 将排序后的桶中的元素依次放回原数组中。

注意事项:

  • 桶排序适用于数据分布均匀的情况。如果数据分布不均匀,可能会导致某些桶中的元素过多,从而影响性能。
  • 桶的数量和桶的大小对性能有很大影响,需要根据具体情况进行调整。
  • 桶排序在处理浮点数时需要注意精度问题,上面的例子使用了 double 类型,但实际应用中可能需要更精细的控制。
相关推荐
All for pursuit.26 分钟前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark33 分钟前
数据压缩算法的时间复杂度与压缩率权衡4
算法
小陈phd1 小时前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法
渡我白衣1 小时前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9924 小时前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
aramae10 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法
荆棘鸟智能11 小时前
城市感知设备怎么统一接入?从多协议网关到设备模型的中间件架构设计
人工智能·算法·边缘计算
淡海水12 小时前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic10112 小时前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
INGNIGHT15 小时前
270 · 电话号码的字母组合II(Trie)
linux·算法