Вы находитесь на странице: 1из 10

Radix Sort

Radix sort is the method to use when


alphabetizing a large list of names
The list of names is first sorted according to
the first letter of each name
That is, the names are arranged in 26 classes
where the first class consists of those names
that begin with A, the second class consists of
those names that begin with B and so on
Radix Sort
The radix sort is a method used by a card
sorter
The cards are first sorted according to the
units digit
On the second pass, the cards are sorted
according to the tens digit
On the third and last pass, the cards are
sorted according to the hundreds digit
Radix Sort
Example: Suppose 6 cards are punched as follows : 348,143,361,321,543,366
a) In the first pass, the units digits are sorted into pockets. Then the cards are now
reinput to the sorter

Values 0 1 2 3 4 5 6 7 8 9

348 348

143 143

361 361

321 321

543 543

366 366
Radix Sort
b) In the second pass, the tens digits are sorted into pockets. Again the cards are
collected pocket by pocket and reinput to the sorter

Values 0 1 2 3 4 5 6 7 8 9

361 361

321 321

143 143

543 543

366 366

348 348
Radix Sort
b) In the third pass, the hundreds are sorted into pockets. When the cards are
collected after the 3rd pass, the numbers are in the following order
143,321,348,361,366,543

Values 0 1 2 3 4 5 6 7 8 9

321 321

143 143

543 543

348 348

361 361

366 366
Radix Sort
Algorithm
sort by the least significant digit first (counting
sort)
=> Numbers with the same digit go to same bin
reorder all the numbers: the numbers in bin 0
precede the numbers in bin 1, which precede the
numbers in bin 2, and so on
sort by the next least significant digit
continue this process until the numbers have been
sorted on all k digits
Radix Sort
Least-significant-digit-first

Example: 275, 087, 426, 061, 509, 170, 677, 503


// base 10
// FIFO

// d times of counting sort

// scan A[i], put into correct slot

// re-order back to original array


Complexity of Radix Sort
Suppose a list A contains n elements. Let d
denote the radix (eg. d=10 for numeric value,
d=26 for letters)
The radix sort algorithm will require s passes
(the number of digits in each item)
Hence the number C(n) of comparisons for the
algorithm is C(n)<= d*s*n
Here d is independent of n and s does depend
on n
In the worst case s=n, so C(n)=O(n2)
In the best case s=log n, so C(n)=O(n log n)

Вам также может понравиться