Chapter7 Part4 Radix Counting
Chapter7 Part4 Radix Counting
Sorting:
Radix Sort & Counting
Sort
Bucket Sort
How would you sort a pile of books?
You could sort the books by the name of the author
Create 26 separate piles, one for each letter of the alphabet
Books by authors whose names start with ‘A’ go in 1st pile,
books by authors whose names start with ‘B’ go in 2nd pile, and
so on…
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
Radix Sort
Let’s apply radix sort to the array [25 5 20 315 11 77]
data = [025
02 0100502020
00315
31 011
07
0 1 077]
5 5 5 7
0 1 2 3 4 5 6 7 8 9
Radix Sort
Let’s apply radix sort to the array [25 5 20 315 11 77]
data = [025
00 0100531020
02315
02 011
07
5 1 077]
5 0 5 7
= [5 11 20 25 77 315]
0 1 2 3 4 5 6 7 8 9
6 7 2 5 1 0 3 4
0 1 2 3 4 5 6 7
What if we treat each element as an index?
Create array tmp where last index is the largest data
value
What if there
are duplicate
0 1 2 3 4 5 6 7 values?
0 1 2 3 4 5 6 7 8 9
count[i] = count[i – 1] +
0 1 2
1 4
2 1
5 5
0 0
5 2
7 0
7 1
8
count[i]
Counting Sort for i = n-1 down to 0
tmp[count[data[i]]-1] =
0 1 2 3 4 5 6 7 data[i];
data[ decrement count[data[i]];
7 2 9 3 7 3 4 1
]
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 9
tmp[ count[
0 1 2 4 5 5 5 7 7 8
] ]
1 0 0 2 4 5 5 5 7 7 8
1 4 0 0 2 4 4 5 5 7 7 8
1 3 4 0 0 2 3 4 5 5 7 7 8
1 3 4 7 0 0 2 3 4 5 5 6 7 8
1 3 3 4 7 0 0 2 2 4 5 5 6 7 8
1 3 3 4 7 9 0 0 2 2 4 5 5 6 7 7
1 2 3 3 4 7 9 0 0 1 2 4 5 5 6 7 7
1 2 3 3 4 7 7 9 0 0 1 2 4 5 5 5 7 7
Counting Sort: Complexity
count occurrences of each number in data[];
store occurrences in count[] indexed with numbers in
data[];
for i = 1 up to count.length-1
count[i] = the number of elements <= i; O(n)
// transfer numbers from data[] to tmp[]
for i = n-1 down to 0 O(n)
tmp[count[data[i]] - 1] = data[i];
decrement count[data[i]]; How many
O(n) times will the
transfer numbers from tmp[] to data[];
loop execute?
O(n +
Total complexity?
max) O(max)