
文章目录
基数排序(Radix Sort)
基数排序属于“分配式排序”(Distribution Sort),它是透过键值的部份信息,将要排序的元素分配至某些“桶”中,藉以达到排序的作用,基数排序法是属于稳定性的排序,其时间复杂度为 ,其中r为所采取的基数,而m为堆数,在某些时候,基数排序法的效率高于其它的稳定性排序法。
示例
public class Program { public static void Main(string[] args) { int[] array = { 43, 69, 11, 72, 28, 21, 56, 80, 48, 94, 32, 8 }; RadixSort(array, 10); ShowSord(array); Console.ReadKey(); } private static void ShowSord(int[] array) { foreach (var num in array) { Console.Write($"{num} "); } Console.WriteLine(); } public static void RadixSort(int[] array, int bucketNum) { int maxLength = MaxLength(array); //创建bucket时,在二维中增加一组标识位,其中bucket[x, 0]表示这一维所包含的数字的个数 //通过这样的技巧可以少写很多代码 int[,] bucket = new int[bucketNum, array.Length + 1]; for (int i = 0; i < maxLength; i++) { foreach (var num in array) { int bit = (int)(num / Math.Pow(10, i) % 10); bucket[bit, ++bucket[bit, 0]] = num; } for (int count = 0, j = 0; j < bucketNum; j++) { for (int k = 1; k <= bucket[j, 0]; k++) { array[count++] = bucket[j, k]; } } //最后要重置这个标识 for (int j = 0; j < bucketNum; j++) { bucket[j, 0] = 0; } } } private static int MaxLength(int[] array) { if (array.Length == 0) return 0; int max = array[0]; for (int i = 1; i < array.Length; i++) { if (array[i] > max) max = array[i]; } int count = 0; while (max != 0) { max /= 10; count++; } return count; //return (int)Math.Log10(max) + 1; } }
以上是基数排序算法的一种实现,以下是这个案例的输出结果:
8 11 21 28 32 43 48 56 69 72 80 94
分析
基数排序算法的时间复杂度为: ,其中r为所采取的基数,m为堆数。
AlgorithmMan

AlgorithmMan by Iori,AlgorithmMan是使用C#开发的一套用于算法演示的工具。
GitHub下载地址:https://github.com/byteflying/AlgorithmManRelease
Dark Mode

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/691。
评论列表(3条)
[…] 原文链接:https://www.byteflying.com/archives/691 […]
666
@奔跑:谢谢支持。