基数排序是基于关键字的排序,排序的原理是基于数的各个位权基数的逐一排序后归并序列得到有序数组
{100000, 98564, 45896, 4589, 1000, 789, 568, 89, 42, 3 }在这十个数据中,最大数100000一共有六位数,假设一个数组中最大数的位数是已知的,可以考虑使用基数排序。
【图片来源于网络】
下面给出代码:
public class Select
{
/// <summary>
/// 链表实现基数排序,需要知道最大的数
/// </summary>
/// <param name="array">源数组</param>
/// <param name="places">最大数位数</param>
/// <returns></returns>
public static int[] RadixSort(int[] array, int places)
{
int mod = 10;
int dev = 1;
List<SingleLinkedList<int>> list=new List<SingleLinkedList<int>>();
//创建十个单链表
for (int i = 0; i < 10; i++)
{
list.Add(new SingleLinkedList<int>());
}
//临时容器
List<int> intlist = new List<int>();
for (int i = 0; i < places; i++, mod *= 10, dev *= 10) //最大数的位数决定遍历的次数
{
for (int j = 0; j < array.Length; j++)
{
int temp = (array[j] % mod) / dev; //选出各个位权的基数
list[temp].AddLast(new MyLLNode<int> { Value = array[j] }); //给0~9中的一个链表添加元素
}
for (int k = 0; k < 10; k++)
{
for (int m = 0; m < list[k].GetLength(); m++)
{
intlist.Add(list[k][m]); //将list[0]的链表第一元素到list[9]的链表最后元素添加的临时容器
}
list[k].Clear(); //清空链表中的数据
}
array = intlist.ToArray(); //转化为数组
intlist.Clear();
}
return array;
}
static void Main()
{
int[] array = new int[10] { 100000, 98564, 45896, 4589, 1000, 789, 568, 89, 42, 3 };
int[] d=RadixSort(array,6);
foreach (int g in d)
{
Console.Write(g+" ");
}
Console.ReadKey();
}
}
/// <summary>
/// 单链表
/// </summary>
/// <typeparam name="T"></typeparam>
class SingleLinkedList<T>
{
public MyLLNode<T> First
{
get;
set;
}
public MyLLNode<T> Last
{
get;
set;
}
public void AddLast(MyLLNode<T> node)
{
if (First == null)
{
First = node;
Last = node;
node.Next = null;
}
else
{
Last.Next = node;
Last = Last.Next;//(Last=node;)
Last.Next = null;
}
}
public int GetLength()
{
if (First == null) return 0;
MyLLNode<T> temp = First;
int count = 1;
while (true)
{
if (temp.Next != null)
{
temp = temp.Next;
count++;
}
else break;
}
return count;
}
public T this[int index]
{
get
{
MyLLNode<T> temp = First;
for (int i = 0; i < index; i++)
{
temp = temp.Next;
}
return temp.Value;
}
}
public void Clear()
{
First = null;
}
}
/// <summary>
/// 节点
/// </summary>
/// <typeparam name="T"></typeparam>
class MyLLNode<T>
{
public T Value
{
get;
set;
}
public MyLLNode<T> Next
{
get;
set;
}
}