Upload
devanshu-taneja
View
139
Download
5
Embed Size (px)
Citation preview
RADIX SORT
RADIX SORT
• Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.
• A positional notation is required, but because integers can represent strings of characters (e.g., names or dates), radix sort is not limited to integers
PSEUDOCODE
• RADIX_SORT (A, d)
1. for i = 1 to d
2. Stable_Sort (A) on digit i
EXAMPLE
• Let’s sort the following array using radix sort:
A[10] =64 8 216 512 27 729 0 1 343 125
PASS 1
A[10] =8 216 512 27 729 0 1 343 12564
PASS 1
Sorted Array after pass 1 (LSD)
A[10] =1 512 343 64 125 216 27 8 7290
PASS 2
A[10] =01 512 343 64 125 216 27 08 72900
PASS 2
Sorted Array after pass 2 :
A[10] =01 08 512 216 125 27 729 343 6400
PASS 3
A[10] =001 008 512 216 125 027 729 343 064000
PASS 3
Sorted Array after pass 3 :
A[10] =001 008 027 064 125 216 343 512 729000
ANALYSIS
• Assume that we use counting sort as the intermediate sort.
• Ө(n+k) per pass (digits in the range 0,….,k)
• d passes
• Total = Ө(d(n+k))
• If k=O(n), Time = Ө(dn)
Can we prove it will work?
• Basis: If d = 1, there’s only one digit, so sorting on that digit sorts the array.
• Inductive Step:
• Assume lower-order digits {j: j<i} are sorted
• Show that sorting next digit i leaves array correctly sorted
• If two digits at position i are different, ordering numbers by that digit is correct.
• If they are the same, numbers are already sorted on the lower-order digits. Since we use a stable sort, the numbers stay in the right order
How to break each key into digits? (Lemma 8.4)
• n keys
• b bits/key
• Break into r-bit digits (r ≤ b). Have d =𝒃
𝒓
• Use counting sort, k = 2𝑟-1
EXAMPLE
• 32- bit keys, 8- bit digits.
• b = 32, r = 8, d = 32/8 = 4
• k = 28 – 1 = 255
• Time = Ө(b/r(n + 2𝑟))
• If b < lgn
(n + 2𝑟) = Ө(n). Thus, choosing r = b yields an optimal running time of (b/b(n + 2𝑏)) = Ө(n)
• If b ≥ lgn
Choosing r = lgn yields a running time of Ө(bn/lgn)
If lgn > r > lgn, Time = Ω(bn/lgn)