/* Exp11-10.cpp */
# Include <stdio. h>
# Include <malloc. h>
# Include <string. h>
# Define maxlen 9/* Maximum length of a word */
# Define Radix 27/* base radix is 27, corresponding to '', 'A',... 'Z '*/
Typedef char string [maxlen + 1];/* defines string as the character array type */
Typedef struct Node
{
String word;
Struct node * next;
} Linknode;
Void dispword (string R [], int N)/* output word */
{
Int I;
Printf ("");
For (I = 0; I <n; I ++)
Printf ("[% s]", R [I]);
Printf ("\ n ");
}
Void preprocess (string R [], int N)/* pre-processes words and fills the end with spaces to maxlen length */
{
Int I, J;
For (I = 0; I <n; I ++)
{
If (strlen (R [I]) <maxlen)
{
For (j = strlen (R [I]); j <maxlen; j ++)
R [I] [J] = '';
R [I] [J] = '\ 0 ';
}
}
}
Void endprocess (string R [], int N)/* restore processing, delete trailing spaces filled during preprocessing */
{
Int I, J;
For (I = 0; I <n; I ++)
{
For (j = MaxLen-1; R [I] [J] = ''; j --);
R [I] [J + 1] = '\ 0 ';
}
}
Void distribute (string R [], linknode * head [], linknode * tail [], Int J, int N)/* distribute by the J-th component of the keyword, each queue must be empty when entering this process */
{
Int I, K;
Linknode * P;
For (I = 0; I <n; I ++)/* scan R [I] in sequence and team it */
{
If (R [I] [J] = '')/* put the space in queue 0, and 'A' put the space in queue 1 ,...*/
K = 0;
Else
K = R [I] [J]-'A' + 1;
P = (linknode *) malloc (sizeof (linknode);/* Create a new node */
Strcpy (p-> word, R [I]);
P-> next = NULL;
If (head [k] = NULL)
{
Head [k] = P;
Tail [k] = P;
}
Else
{
Tail [k]-> next = P;
Tail [k] = P;
}
}
}
Void collect (string R [], linknode * head [])/* collect records from non-empty queues in sequence */
{
Int K = 0, I;
Linknode * P;
For (I = 0; I <Radix; I ++)
For (P = head [I]; P! = NULL; P = p-> next)
Strcpy (R [k ++], p-> word );
}
Void radixsort (string R [], int N)/* sorts the base number of R [0... n-1 */
{
Linknode * head [Radix], * tail [Radix];/* define Radix queues */
Int I, J;
For (I = MaxLen-1; I> = 0; I --)/* sort from low to high */
{
For (j = 0; j <Radix; j ++)
Head [J] = tail [J] = NULL;/* empty queue */
Distribute (R, Head, tail, I, n);/* I allocation */
Collect (R, head);/* I-th Collection */
}
}
Void main ()
{
Int n = 6;
String R [] = {"while", "if", "If else", "do while", "for", "case "};
Printf ("Before sorting: \ n"); dispword (R, N );
Preprocess (R, N );
Printf ("after preprocessing; \ n"); dispword (R, N );
Radixsort (R, N );
Printf ("sorting result: \ n"); dispword (R, N );
Endprocess (R, N );
Printf ("final result: \ n"); dispword (R, N );
}