Algorithm R
Algorithm R (Radix list sort). Records R1,…, RN are each assumed to contain
a LINK field. Their keys are assumed to be p-tuples
(a1,a2,…,ap), 0 <= ai < M, (1)
where the order is defined lexicographically so that
(a1,a2,…,ap) < (b1,b2,… ,bp) (2)
if and only if for some j, 1 <= j <= p, we have
ai = bi for all i < j, but aj < bj. (3)
The keys may, in particular, be thought of as numbers written in radix M
notation,
a1M^(p-1) + a2M^(p-2) … + ap-1M + ap, (4)
and in this case lexicographic order corresponds to the normal ordering of non-
negative numbers. The keys may also be strings of alphabetic letters, etc.
Sorting is done by keeping M “piles” of records, in a manner that exactly
parallels the action of a card sorting machine. The piles are really queues in the
sense of Chapter 2, since we link them together so that they are traversed in a
first-in-first-out manner. There are two pointer variables TOP[i] and BOTM[i]
for each pile, 0 <= i < M, and we assume as in Chapter 2 that
LINK(LOC(BOTM[i])) = BOTM[i]. (5)
R1. [Loop on k.] In the beginning, set P <– LOC(RN), a pointer to the last
record. Then perform steps R2 through R6 for k = 1,2,… ,p. (Steps R2
through R6 constitute one “pass.”) Then the algorithm terminates, with
P pointing to the record with the smallest key, LINK(P) to the record with
next smallest, then LINK (LINK (P)), etc.; the LINK in the final record will
be Null.
R2. [Set piles empty.] Set TOP[i] <– LOC(BOTM[i]) and BOTM[i] <– Null, for
0 <= i < M.
R3. [Extract kth digit of key.] Let KEY(P), the key in the record referenced by P,
be (a1, a2,…, ap); set i <– ap+1-k, the kth least significant digit of this key.
R4. [Adjust links.] Set LINK (TOP[i]) <– P, then set TOP[i] <– P.
R5. [Step to next record.] If k = 1 (the first pass) and if P = LOC(Rj), for some
j !=1, set P <– LOC(Rj-1) and return to R3. If k > 1 (subsequent passes),
set P <– LINK(P), and return to R3 if P != Null.
R6. [Do Algorithm H.] (We are now done distributing all elements onto the
piles.) Perform Algorithm H below, which “hooks together” the individual
piles into one list, in preparation for the next pass. Then set P <– BOTM[0],
a pointer to the first element of the hooked-up list. (See exercise 3.) |
Algorithm H
Algorithm H (Hooking-up of queues). Given M queues, linked according to
the conventions of Algorithm R, this algorithm adjusts at most M links so that
a single queue is created, with BOTM[0] pointing to the first element, and with
pile 0 preceding pile 1 … preceding pile M-1.
H1. [Initialize.] Set i <– 0.
H2. [Point to top of pile.] Set P <– TOP[i].
H3. [Next pile.] Increase i by 1. If i = M, set LINK(P) <– Null and terminate the
algorithm.
H4. [Is pile empty?] If BOTM