(Latest Revision: 03/15/2008)

Radix Sort




Explanation of the Algorithm

We are given a totally ordered set of symbols and a list of N K-symbol strings
to sort.  Here is an example with N=12 and K=3:

456 111 793 881 567 536 709 974 734 581 695 586

We need a queue for each possible symbol occurring in the strings.  Usually
it's best if the queues are implemented as linked lists, so we don't need
static allocation of sufficient room in each queue for the entire list to be
sorted.  

The first thing to do is to traverse the list from left to right, and put each
element in the queue corresponding to the last symbol in the string (here the
last digit).

        581                      586
        881            734       536    
        111       793  974  695  456  567       709
    0     1    2    3    4    5    6    7    8    9

We then place some sort of 'marker' in each queue.

        000                      000
        581            000       586
        881       000  734  000  536  000       000
  000   111  000  793  974  695  456  567  000  709
    0     1    2    3    4    5    6    7    8    9

In the next phase of the sort, we move from queue to queue, according to the
ascending order of the symbols.  We remove elements from each queue.  We
requeus each list element according to the symbol in the second to last
position.  When we dequeue the marker, we discard it (without requeuing) and
move along to the next queue, if any remain.  After all the list elements are
re-queued, we place markers in all the queues again.

                                            000
                   000                      586  000
   000   000       536       000  000  000  581  695
   709   111  000  734  000  456  567  974  881  793
    0     1    2    3    4    5    6    7    8    9

We keep on like this, doing a pass for each position in the strings. Near the
end, we have the strings queued by the first symbol:

                              586
                              581       793
                              567       734
          111            456  536  695  709  881  974
    0     1    2    3    4    5    6    7    8    9

If we now simply empty the queues in order, we will get the list elements in
ascending order:

111 456 536 567 581 586 695 709 734 793 881 974

How efficient is radix sort?  There's some information about that 
here.