基数排序

基数排序

 

   1 //C语言里这个符号&不能用在形参指针替代

  2 #include<stdio.h>
  3 #include<string.h>
  4 
  5 #define MAX_NUM_OF_KEY 8
  6 #define RADIX 10
  7 #define MAX_SPACE 10000
  8 typedef char KeysType;
  9 typedef int InfoType;
 10 
 11 typedef struct SLCell
 12 {
 13     KeysType keys[MAX_NUM_OF_KEY];
 14     int next;
 15 } SL;
 16 
 17 typedef struct
 18 {
 19     SL r[MAX_SPACE];
 20     int keynum;
 21     int recnum;
 22 } SLList;
 23 typedef int ArrType[RADIX];
 24 
 25 int ord(char a)
 26 {
 27     return a-'0';
 28 }
 29 
 30 void Print(SLList L)
 31 {
 32     int i;
 33     for(i=L.r[0].next; i; i=L.r[i].next)printf("%s ",L.r[i].keys);
 34     printf("\n");
 35 }
 36 
 37 //void Distribute(SLList &L,int i,ArrType &f,ArrType &e)
 38 void Distribute(SLList *L,int i,ArrType f,ArrType e)
 39 {
 40     int j,p;
 41     for(j=0; j<RADIX; j++)f[j]=0;
 42     for(p=L->r[0].next; p; p=L->r[p].next)
 43     {
 44         j=ord(L->r[p].keys[i]);
 45         if(!f[j])f[j]=p;
 46         else L->r[e[j]].next=p;
 47         e[j]=p;
 48     }
 49 }
 50 
 51 //void Collect(SLList &L,int i,ArrType f,ArrType e)
 52 void Collect(SLList *L,int i,ArrType f,ArrType e)
 53 {
 54     int j,t;
 55     for(j=0; !f[j]; j++);
 56     L->r[0].next=f[j];
 57     t=e[j];
 58     while(j<RADIX-1)
 59     {
 60         for(j++; j<RADIX-1&&!f[j]; j++);
 61         if(f[j])
 62         {
 63             L->r[t].next=f[j];
 64             t=e[j];
 65         }
 66     }
 67     L->r[t].next=0;
 68 }
 69 
 70 //void RadixSort(SLList &L)
 71 void RadixSort(SLList *L)
 72 {
 73     int i;
 74     ArrType f,e;
 75     for(i=0; i<L->recnum; i++)
 76     L->r[i].next=i+1;
 77 
 78     L->r[L->recnum].next=0;
 79     for(i=L->keynum-1; i>=0; i--)
 80     {
 81         Distribute(L,i,f,e);
 82         Collect(L,i,f,e);
 83         Print(*L);
 84     }
 85 }
 86 
 87 int main()
 88 {
 89     int n,i;
 90     unsigned int max=0;
 91     char a[8];
 92     SLList L;
 93     scanf("%d",&n);                                        //用软编码吧!
 94     for(i=1; i<=n; i++)
 95     {
 96         scanf("%s",a);
 97         strcpy(L.r[i].keys,a);
 98         if(strlen(a)>max)max=strlen(a);
 99     }
100     L.keynum=max;
101     L.recnum=n;
102     RadixSort(&L);
103     return 0;
104 }
posted @ 2012-04-27 16:45  zhengmian  阅读(214)  评论(0)    收藏  举报