C# 排序算法 基数排序
使用环境 vs2017 .net core 2.1 控制台程序
实现方式: 基数排序属于“分配式排序”(Distribution Sort),它是透过键值的部份信息,将要排序的元素分配至某些“桶”中,藉以达到排序的作用,基数排序法是属于稳定性的排序,其时间复杂度为 O (n*log®*m) ,其中r为所采取的基数,而m为堆数,在某些时候,基数排序法的效率高于其它的稳定性排序法。
// 记录外部循环次数
public static int outListInt { get; set; }
// 记录内部循环次数
public static int inListInt { get; set; }
// 记录排序次数
public static int sortListInt { get; set; }
static void Main(string[] args)
{
Console.WriteLine("基数排序-示例");
// 初始化 list 无序列表 加入一个非常大的数据
List<int> sortList = new List<int>();
//
int[] baseIntList = new int[]
{
65, 1, 5, 2, 7, 11, 2, 4, 3
};
//
RadixSort(baseIntList, 8);
//
Console.WriteLine();
//
Console.WriteLine("外部循环次数:" + outListInt);
Console.WriteLine("内部循环次数:" + inListInt);
Console.WriteLine("排 序 次 数:" + sortListInt);
//
OutputResult("输出结果", baseIntList.ToList());
Console.ReadKey();
}
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++)
{
outListInt += 1;
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++)
{
inListInt += 1;
for (int k = 1; k <= bucket[j, 0]; k++)
{
// 输出
Console.WriteLine();
OutputResult("交换之前", array.ToList());
Console.Write(String.Format(" {0:D}<-交换->{1:D} ", array[j], array[j + 1]));
array[count++] = bucket[j, k];
// 输出
OutputResult("交换之后", array.ToList());
sortListInt += 1;
}
}
//最后要重置这个标识
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;
}
/// <summary>
/// 格式化输出
/// </summary>
/// <param name="outputString">输出标题</param>
/// <param name="baseIntLsit">输出内容</param>
private static void OutputResult(string outputString, List<int> baseIntLsit)
{
Console.Write(outputString + ":");
foreach (int itemInt in baseIntLsit)
{
Console.Write(itemInt + " ");
}
}