《数据结构与算法分析-C语言描述》[3. 13]
利用社会安全号码对学生记录构成的数组排序。编写一个程序进行这项工作,使用具有1000个桶的基数排序并分三趟进行。
文件1:源文件
#include"list.h"
bucketSort(ElementType a[NUM], int sortTimes){
int i,j;
List bucket[BUKNUM];
for (i = 0; i < BUKNUM; i++){ /*创建1000个桶*/
bucket[i] = CreatList();
}
for (i = 0; i < sortTimes; i++){ /*三次桶排序*/
// printfArray(a);
for (j = 0; j < BUKNUM; j++){ /*把桶里的数据清空*/
MakeEmpty(bucket[j]);
}
for (j = 0; j < NUM; j++){ /*将数组数据装桶*/
InsertOfEnd(a[j], bucket[((int)(a[j] / pow(1000, i)) % 1000)]);/*表头插入和表尾插入一样吗*/
}
int k = 0;
for (j = 0; j < BUKNUM; j++){ /*按桶顺序放回数组*/
Position p = bucket[j]->Next;
while (p){
a[k++] = p->Element;
p = p->Next;
}
}
}
}
int main(){
int arr[NUM] = { 123456789, 56, 436456757, 454345, 234567890, 985333222, 555333, 24678535, 044444, 66666666, 33332, 754676, 867546734, 456343225, 4654636 };
int sortTimes = 3; /*排序次数*/
printfArray(arr);
bucketSort(arr, 3);
printfArray(arr);
return 0;
}
文件2:list.h
#ifndef _LIST_H
#include
#include
#include
typedef struct Node *List;
typedef List Position;
typedef int ElementType;
#define NUM 15 /*需要排序的数字数量*/
#define BUKNUM 1000 /*桶的数量*/
struct Node{
ElementType Element;
Position Next;
};
printfArray(ElementType a[NUM]){
int i;
printf("\n");
for (i = 0; i < NUM; i++){
printf("%d ", a[i]);
}
printf("\n");
}
List CreatList(){
List P = (List)malloc(sizeof(struct Node));
P->Next = NULL;
return P;
}
MakeEmpty(List HeadNode){
Position P = HeadNode->Next;
HeadNode->Next = NULL;
Position aftP;
while (P){
aftP = P->Next;
free(P);
P = aftP;
}
}
InsertOfEnd(ElementType a,List HeadNode){
Position L = (Position)malloc(sizeof(struct Node));
L->Element = a;
L->Next = NULL;
Position p = HeadNode;
while (p->Next != NULL) {
p = p->Next;
}
p->Next = L;
}
#endif