原理
将待排序数,按照个位,一次进桶,再按桶的顺序依此出桶,再按十尾依此进桶出桶,再按百位进同出桶。。。步骤
(1)设置一个定量的数组当作空桶子;
(2)寻访序列,并且按照要求把记录一个一个放到对应的桶子去;
(3)对每个不是空的桶子进行排序。
(4)从不是空的桶子里把项目再放回原来的序列中。
性能
稳定性:稳定
时间复杂度:O(d*n)(d表示趟数 )
空间复杂度:O(n)实现
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node
{
int data;
struct Node *next;
}Node,*List;
void Init(List plist)
{
assert(plist != NULL);
plist->next = NULL;
}
static Node *BuyNode(int val)
{
Node *p = (Node*)malloc(sizeof(Node));
assert(p !=NULL);
p->data = val;
p->next = NULL;
return p;
}
void Insert(List plist,int val)
{
Node *p = plist;
for(;p->next != NULL;p=p->next)
{
;
}
Node *q = BuyNode(val);
p->next = q;
}
bool DeleteFirst(List plist,int *rtval)
{
Node *p = plist->next;
if (p == NULL)
{
/* code */
return false;
}
*rtval = p->data;
plist->next = p->next;
free(p);
return true;
}
int GetNum(int num,int figure)
{
for (int i = 0; i < figure; ++i)
{
/* code */
num /= 10;
}
return num %10;
}
int GetMaxFigure(int *arr,int len)
{
int max = arr[0];
int count = 0;
for (int i = 0; i < len; ++i)
{
/* code */
if (arr[i] > max)
{
/* code */
max = arr[i];
}
}
while(max != 0)
{
count++;
max /= 10;
}
return count;
}
void Radix(int *arr,int len,int figure)
{
int tmp;
Node head[10];
int i = 0;
for (i = 0; i < 10; ++i)
{
/* code */
Init(&head[i]);
}
for (i = 0; i < len; ++i)
{
/* code */
tmp = GetNum(arr[i],figure);
Insert(&head[tmp],arr[i]);
}
i = 0;
for (int j = 0; j < 10; )
{
/* code */
if (DeleteFirst(&head[j],&arr[i]))
{
/* code */
i++;
}
else
{
j++;
}
}
}
void RadixSort(int *arr,int len)
{
int figure = GetMaxFigure(arr,len);
for (int i = 0; i < figure; ++i)
{
/* code */
Radix(arr,len,i);
}
}