Radix Sort
Radix Sort
* Thanks to Richard Ladner for this fact, taken from Winter 1999 CSE 326 course web.
1
RadixSort – magic! It works.
• Input list:
126, 328, 636, 341, 416, 131, 328
• BinSort on lower digit:
341, 131, 126, 636, 416, 328, 328
• BinSort result on next-higher digit:
416, 126, 328, 328, 131, 636, 341
• BinSort that result on highest digit:
126, 131, 328, 328, 341, 416, 636
2
Not magic. It provably works.
• Keys
– N-digit numbers
– base B
• Claim: after ith BinSort, least significant i
digits are sorted.
– e.g. B=10, i=3, keys are 1776 and 8234. 8234
comes before 1776 for last 3 digits.
3
Induction to the rescue!!!
• base case:
– i=0. 0 digits are sorted (that wasn’t hard!)
4
Induction is rescuing us…
• Induction step
– assume for i, prove for i+1.
– consider two numbers: X, Y. Say Xi is ith digit
of X (from the right)
• Xi+1 < Yi+1 then i+1th BinSort will put them in order
• Xi+1 > Yi+1 , same thing
• Xi+1 = Yi+1 , order depends on last i digits. Induction
hypothesis says already sorted for these digits.
(Careful about ensuring that your BinSort preserves
order aka “stable”…)
5
Running time of Radixsort
• How many passes?
• How much work per pass?
• Total time?
• Conclusion
– Not truly linear if K is large.
• In practice
– RadixSort only good for large number of items, relatively
small keys
– Hard on the cache, vs. MergeSort/QuickSort
6
What data types can you
RadixSort?
• Any type T that can be BinSorted
• Any type T that can be broken into parts A
and B,
– You can reconstruct T from A and B
– A can be RadixSorted
– B can be RadixSorted
– A is always more significant than B, in ordering
7
Example:
• 1-digit numbers can be BinSorted
• 2 to 5-digit numbers can be BinSorted
without using too much memory
• 6-digit numbers, broken up into A=first 3
digits, B=last 3 digits.
– A and B can reconstruct original 6-digits
– A and B each RadixSortable as above
– A more significant than B
8
RadixSorting Strings
• 1 Character can be BinSorted
• Break strings into characters
• Need to know length of biggest string (or
calculate this on the fly).
9
RadixSorting Strings example
5th 4th 3rd 2nd 1st
pass pass pass pass pass
String 1 z i p p y
String 2 z a p NULLs are
just like fake
String 3 a n t s characters
String 4 f l a p s
10