At the end, we concatenate the bins in order to obtain a list L.
= right most digit of i
Bin | ||||||
0 |
|
|||||
1 |
|
|
||||
2 | ||||||
3 | ||||||
4 |
|
|
||||
5 |
|
|||||
6 |
|
|
||||
7 | ||||||
8 | ||||||
9 |
|
|
L: 0, 1, 81, 64, 4, 25, 36, 16, 9, 49
= right most digit of i
Bin | ||||||||||||
0 |
|
|
|
|
||||||||
1 |
|
|||||||||||
2 |
|
|||||||||||
3 |
|
|||||||||||
4 |
|
|||||||||||
5 | ||||||||||||
6 |
|
|||||||||||
7 | ||||||||||||
8 |
|
|||||||||||
9 |
0, 1, 4, 9, 25, 36, 49, 64, 81
Suppose it is required to sort the records in lexicographic order of their keys. That is,
1. | a1 < b1 |
2. | a1 = b1;a2 < b2 |
3. | a1 = b1;a2 = b2;a3 < b3 |
. | |
. | |
. | |
k. | a1 = b1;...;ak - 1 = bk - 1;ak < bk |
Radix sort proceeds in the following way.
First binsort all records first on fk, the least significant digit, then concatenate the bins lowest value first.
Then binsort the above concatenated list on fk - 1 and then concatenate the bins lowest value first.
In general, after binsorting on fk,
fk - 1,..., fi, the records will
appear in lexicographic order if the key consisted of only the fieldsfi,...,
fk.
void radixsort;
/ * Sorts a list A of n records with keys consisting of fields
f1,..., fk of types t1,..., tk. The function uses k
arrays B1,..., Bk of type array [ti] of list-type, i = 1,..., k,
where list-type is a linked list of records */
{
for(i = k;i 1;i - -)
{
for (each value v of type ti)
make Bi[v] empty; /* clear bins */
for (each value r on list A)
move r from A onto the end of bin Bi[v],
where v is the value of the field fi of the key of r;
for (each value v of type ti from lowest to highest)
concatenate Bi[v] onto the end of A
}
}
Thus the total time
= | O(si + n) | ||
= | Okn + si | ||
= | On + si |
Thus si = n and total running time is O(n)