- 思想:
将多个数按由低位到高位的顺序依次放入桶中。输出时将桶的数据构成一个新的链表。
举个例子:将0,1,512,343,64,125,216,27,8,729.进行排序。(因为最大数为729为三位所以进行三趟排序)
按照个位进行第一趟排序:
![7edf6ff539ed11ba81f23cc951e6930f.png](https://img-blog.csdnimg.cn/img_convert/7edf6ff539ed11ba81f23cc951e6930f.png)
按照十位排序:
![fd2f5f0e4376783d8125bd99a729b6cb.png](https://img-blog.csdnimg.cn/img_convert/fd2f5f0e4376783d8125bd99a729b6cb.png)
按照百位进行排序:
![c6eae44d13013b3ae5eab11d6e54bcd4.png](https://img-blog.csdnimg.cn/img_convert/c6eae44d13013b3ae5eab11d6e54bcd4.png)
易错:
如果思想理解的话,仍需要几点注意。桶是由结构体数组组成而不是链表。而且注意链表中的数据放入桶中的过程也是构造一个新链表的过程,而输出时又是从由桶构成的链表中的数据构成一个新链表的过程。代码书写的话这个过程理解的话就好办了。
时间复杂度:
O(P(N+B)),p为排序的趟数,B为桶数
代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define bucket 10
#define LENGTH sizeof(struct node)
//定义一个节点
typedef struct node
{
int data;
struct node* next;
}*List, *Node;
//判断结点是否为空
int IsEmpty(List L) {
return L->next == NULL;
}
//判断是否为最后一个结点
int IsLast(List L) {
return L->next == NULL;
}
//初始化结点(头结点)
List Init_List(void) {
Node L = (Node)malloc(LENGTH);
if (L == NULL)
printf("out of space");
L->next = NULL;
return L;
}
//遍历链表
void Print_List(Node phead)
{
Node p = phead->next;//跳过头结点进行遍历
while (p != NULL)//尾结点为空时终止(尾结点的指针域为空)
{
printf("%dt", p->data);
p = p->next;
}printf("n");
}
//根据链表中最大的数决定排序趟数
int SortNum(Node L) {
Node p = L->next;
int x=0,count=0;
for (; p != NULL; p = p->next) {
if (x<p->data) {
x = p->data;
}
}
while (x) {
x /= 10;
count++;
}
return count;
}
void MoveNode(Node L1,Node L2) {
Node temp;
while (!IsLast(L1)) {
L1 = L1->next;
}
if (L2->next ==NULL)
exit(-1);//表或桶为空时结束
temp = L2;
L2 = L2->next;
temp->next = L2->next;//相当于在链表移除结点L2,到放到桶(结构体数组)中收集
L1->next = L2;
L2->next = NULL;
}
//创建一个单链表(尾插法)
List Create_List(Node L)
{
Node p;
Node tail = L;
int a;
int len;
printf("请输入要排序的个数:");
scanf_s("%d", &len);
printf("请输入元素:n");
for (int i = 0; i < len; i++)
{
p = (Node)malloc(LENGTH);
if (p ==NULL)
return 0;
scanf_s("%d", &a);
tail->next = p;
p->data = a;
p->next = NULL;
tail = p;
}
return L;//f返回头结点
}
void RaidSort(Node L) {
Node b[bucket];
int i,Element,sum;
for ( i = 0; i < bucket; i++) {
b[i] = Init_List();
}
int num = SortNum(L);//num为趟数
for (i = 0; i < num; i++) {
while (!IsEmpty(L)) {
Element = L->next->data;
sum = (int)(Element / pow(10, i)) % 10;//根据num的值,按照个位十位,,,(低位到高位放入桶中)
MoveNode(b[sum],L);
}
for (int j = 0; j < 10; j++) {
while (!IsEmpty(b[j]))
{
MoveNode(L,b[j]);
}
}
printf("第%d轮排序:n", i + 1);
Print_List(L);
}
for (int i = 0; i < bucket; i++)
free(b[i]);//排序完成释放桶
}
int main()
{
Node s;
s=Init_List();
Create_List(s);
Print_List(s);
RaidSort(s);
return 0;
}
结果:
![6857d20f97b7efcc62292a65db20e3dc.png](https://img-blog.csdnimg.cn/img_convert/6857d20f97b7efcc62292a65db20e3dc.png)
![d0d3e9d96523991030cf7a3089b3f85a.png](https://img-blog.csdnimg.cn/img_convert/d0d3e9d96523991030cf7a3089b3f85a.png)
参考书籍:
数据结构算法与分析第二版