第十六周项目1(8)-基数排序
2015-12-14 17:02
525 查看
问题及代码:
用序列{57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7}作为测试数据,运行并本周视频中所讲过的算法对应 程序,观察运行结果并深刻领会算法的思路和实现方法:
(8)基数排序
代码如下:
运行结果:
用序列{57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7}作为测试数据,运行并本周视频中所讲过的算法对应 程序,观察运行结果并深刻领会算法的思路和实现方法:
(8)基数排序
代码如下:
#include <stdio.h> #include <malloc.h> #include <string.h> #define MAXE 20 //线性表中最多元素个数 #define MAXR 10 //基数的最大取值 #define MAXD 8 //关键字位数的最大取值 typedef struct node { char data[MAXD]; //记录的关键字定义的字符串 struct node *next; } RecType; void CreaLink(RecType *&p,char *a[],int n); void DispLink(RecType *p); void RadixSort(RecType *&p,int r,int d) //实现基数排序:*p为待排序序列链表指针,r为基数,d为关键字位数 { RecType *head[MAXR],*tail[MAXR],*t; //定义各链队的首尾指针 int i,j,k; for (i=0; i<=d-1; i++) //从低位到高位循环 { for (j=0; j<r; j++) //初始化各链队首、尾指针 head[j]=tail[j]=NULL; while (p!=NULL) //对于原链表中每个结点循环 { k=p->data[i]-'0'; //找第k个链队 if (head[k]==NULL) //进行分配 { head[k]=p; tail[k]=p; } else { tail[k]->next=p; tail[k]=p; } p=p->next; //取下一个待排序的元素 } p=NULL; //重新用p来收集所有结点 for (j=0; j<r; j++) //对于每一个链队循环 if (head[j]!=NULL) //进行收集 { if (p==NULL) { p=head[j]; t=tail[j]; } else { t->next=head[j]; t=tail[j]; } } t->next=NULL; //最后一个结点的next域置NULL //以下的显示并非必要 printf(" 按%d位排序\t",i); DispLink(p); } } void CreateLink(RecType *&p,char a[MAXE][MAXD],int n) //采用后插法产生链表 { int i; RecType *s,*t; for (i=0; i<n; i++) { s=(RecType *)malloc(sizeof(RecType)); strcpy(s->data,a[i]); if (i==0) { p=s; t=s; } else { t->next=s; t=s; } } t->next=NULL; } void DispLink(RecType *p) //输出链表 { while (p!=NULL) { printf("%c%c ",p->data[1],p->data[0]); p=p->next; } printf("\n"); } int main() { int n=10,r=10,d=2; int i,j,k; RecType *p; char a[MAXE][MAXD]; int b[]= {75,23,98,44,57,12,29,64,38,82}; for (i=0; i<n; i++) //将b[i]转换成字符串 { k=b[i]; for (j=0; j<d; j++) //例如b[0]=75,转换后a[0][0]='7',a[0][1]='5' { a[i][j]=k%10+'0'; k=k/10; } a[i][j]='\0'; } CreateLink(p,a,n); printf("\n"); printf(" 初始关键字\t"); //输出初始关键字序列 DispLink(p); RadixSort(p,10,2); printf(" 最终结果\t"); //输出最终结果 DispLink(p); printf("\n"); return 0; }1
运行结果:
相关文章推荐
- 第十六周 项目一 (2) 插入排序之排序中输出每一趟的中间结果
- [宇宙与天文]灵魂星体投射
- jboss加密敏感信息
- Android学习路线图
- 12月14号 宏定义、枚举和动态分配内存
- 第14周项目4(3)输出所有路径
- 第十六周 项目一 验证算法(6) 堆排序
- device_add()浅析
- 第14周SHH数据结构-【项目1-(2)验证分块查找算法】
- 第十五周项目一:验证算法
- 第十六周--归并排序算法的改进
- 第十六周——【项目2 - 大数据集上排序算法性能的体验】
- js 异步上传图片 限制图片的格式大小
- 浏览器兼容测试最坑爹,费时费力;今天推荐一个在线的浏览器兼容测试服务
- logback与Log4J的区别
- TinyOS论文09:Random Testing of Interrupt-Driven Software
- 浏览器兼容测试最坑爹,费时费力;今天推荐一个在线的浏览器兼容测试服务
- gulp压缩文件
- 第12周项目4(2)输出简单路径
- 第十二周 项目1 图基本算法库