C#桶排序算法

前言

桶排序是一种线性时间复杂度的排序算法,它将待排序的数据分到有限数量的桶中,每个桶再进行单独排序,最后将所有桶中的数据按顺序依次取出,即可得到排序结果。

实现原理

  1. 首先根据待排序数据,确定需要的桶的数量。

  2. 遍历待排序数据,将每个数据放入对应的桶中。

  3. 对每个非空的桶进行排序,可以使用快速排序、插入排序等常用的排序算法。

  4. 将每个桶中的数据依次取出,即可得到排序结果。

代码实现

复制代码
        public static void BucketSort(int[] array)
        {
            int arrLength = array.Length;
            if (arrLength <= 1)
            {
                return;
            }

            //确定桶的数量
            int maxValue = array[0], minValue = array[0];
            for (int i = 1; i < arrLength; i++)
            {
                if (array[i] > maxValue)
                    maxValue = array[i];
                if (array[i] < minValue)
                    minValue = array[i];
            }
            int bucketCount = (maxValue - minValue) / arrLength + 1;

            //创建桶并将数据放入桶中
            List<List<int>> buckets = new List<List<int>>(bucketCount);
            for (int i = 0; i < bucketCount; i++)
            {
                buckets.Add(new List<int>());
            }

            for (int i = 0; i < arrLength; i++)
            {
                int bucketIndex = (array[i] - minValue) / arrLength;
                buckets[bucketIndex].Add(array[i]);
            }

            //对每个非空的桶进行排序
            int index = 0;
            for (int i = 0; i < bucketCount; i++)
            {
                if (buckets[i].Count == 0)
                {
                    continue;
                }

                int[] tempArr = buckets[i].ToArray();
                Array.Sort(tempArr);

                foreach (int num in tempArr)
                {
                    array[index++] = num;
                }
            }
        }

        public static void BucketSortRun()
        {
            int[] array = { 19, 27, 46, 48, 50, 2, 4, 44, 47, 36, 38, 15, 26, 5, 3, 99, 888};
            Console.WriteLine("排序前数组:" + string.Join(", ", array));

            BucketSort(array);

            Console.WriteLine("排序后数组:" + string.Join(", ", array));
        }

运行结果

总结

桶排序是一种线性时间复杂度的排序算法,适用于待排序数据分布均匀的情况。它通过将数据分到有限数量的桶中,再对每个桶单独进行排序,最后将桶中的数据按顺序组合起来,得到排序结果。桶排序的时间复杂度为O(n+k),其中n为待排序数据的数量,k为桶的数量。但当数据分布不均匀时,可能会导致某些桶的数据较多,需要进行更多的排序操作,使得效率下降。

相关推荐
爱coding的橙子18 分钟前
每日算法刷题Day78:10.23:leetcode 一般树7道题,用时1h30min
算法·leetcode·深度优先
Swift社区20 分钟前
LeetCode 403 - 青蛙过河
算法·leetcode·职场和发展
地平线开发者21 分钟前
三种 Badcase 精度验证方案详解与 hbm_infer 部署实录
算法·自动驾驶
papership32 分钟前
【入门级-算法-5、数值处理算法:高精度的减法】
算法·1024程序员节
lingran__36 分钟前
算法沉淀第十天(牛客2025秋季算法编程训练联赛2-基础组 和 奇怪的电梯)
c++·算法
DuHz1 小时前
基于MIMO FMCW雷达的二维角度分析多径抑制技术——论文阅读
论文阅读·物联网·算法·信息与通信·毫米波雷达
Dragon_D.1 小时前
排序算法大全——插入排序
算法·排序算法·c·学习方法
chao1898442 小时前
C#模拟鼠标键盘操作的多种实现方案
开发语言·c#·计算机外设
大数据张老师2 小时前
数据结构——红黑树
数据结构·算法·红黑树
future_studio2 小时前
聊聊 Unity(小白专享、C# 小程序 之 联机对战)
unity·小程序·c#