源码例如以下: #include <stdlib.h> #include <stdio.h> typedef struct QUEUEnode* link; struct QUEUEnode{ int item ; link next; link head , tail; }; link NEW(int item, link next){ link x = (link) malloc(sizeof *x); x->item = item; x->next = next; return x; } void QUEUEinit(link queue, int maxN){ queue->head = NULL; } int QUEUEempty(link queue){ return queue->head == NULL; } void QUEUEput(link queue,int item){ if(queue->head == NULL){ queue->head =(queue->tail = NEW(item,queue->head)) ; return; } queue->tail->next = NEW(item,queue->tail->next); queue->tail = queue->tail->next; } int QUEUEget(link queue){ int item = queue->head->item; link t = queue->head->next; free(queue->head); queue->head = t; return item; }
//以上是QUEUE的ADT
//求整数k的第p位 int radix(int k, int p){ int i,power = 1 ; for(i=1;i<=p-1;i++) power*=10; return (k%(power*10))/power; } void p(link A){ while(!QUEUEempty(A)) printf("%d ",QUEUEget(A)); } void radixSort(int figure, link A){ //figure:待排序的数据最大位数 此方法仅仅适合数字排序 link Q[10]; int data, pass, i , r; for(pass=1;pass<=figure;pass++){ for(i=0;i<=9;i++){ Q[i] = (link)malloc(sizeof *(Q[i])); QUEUEinit(Q[i],40); //置空队列 } while(!QUEUEempty(A)){ data = QUEUEget(A); r = radix(data,pass); QUEUEput(Q[r],data); //分别往十个队列里分发数据 } for(i=0;i<=9;i++) //这里的操作还能够再优化 while(!QUEUEempty(Q[i])) QUEUEput(A,QUEUEget(Q[i])); //最后往目标队列回收各数位排好序的数据 } } main(){ int a[10] = {321,234,666,745,245,12,23,1,555,651}; link A = (link)malloc(sizeof*A); QUEUEinit(A,10); int i; for(i=0;i<10;i++)QUEUEput(A,a[i]); radixSort(3,A); p(A); }
时间: 2024-10-14 20:51:26