Bucket Sort - UNIT I - Sorting
Bucket Sort - UNIT I - Sorting
Syllabus
• Bucket Sort
• Radix Sort
• Counting Sort
• Analysis of algorithms.
Sorting
• Examples of sorting:
– List containing exam scores sorted from Lowest to Highest or from
Highest to Lowest
– List containing words that were misspelled and be listed in
alphabetical order.
– List of student records and sorted by USN or alphabetically by first or
last name.
Sorting
Ascending order Descending order
st
alle
sm
t to
rg est g e s
t t o la Lar
a ll e s
Sm
Why do we sort?
– For searching on unsorted data by comparing keys, optimal solutions require (n) comparisons.
– For searching on sorted data by comparing keys, optimal solutions require (log n)
comparisons.
• Radix Sort
• Counting sort
8
How Fast Can We Sort?
• Assumption:
– the input is generated by a random process that distributes elements
uniformly over [0, 1)
Bucket Sort
• Idea:
5 .72 4 / Distribute
6 .94 5 / Into buckets
7 .21 6 .68 /
9 .23 8 /
10 .68 9 .94 /
Bucket Sort - Example
0 /
1 .12 .17 /
3 .39 /
Sort within each
4 /
bucket
5 /
6 .68 /
7 .72 .78 /
8 /
9 .94 / 16
Bucket Sort - Example
.12 .17 .21 .23 .26 .39 .68 .72 .78 .94 /
0 /
1 .12 .17 /
3 .39 /
4 /
5 /
6 .68 /
7 .72 .78 /
Concatenate the lists from
8 / 0 to n – 1 together, in order
9 .94 /
Bucket Sort – Example 2
2
0 1 2 3
0 1 2 3 4
0 2 4
0 0 0 1 1 2 2 2 2 3 3 4 4
Bucket Sort - Sorting integers
for i ← 1 to n O(n)
for i ← 0 to n - 1
k O(n/k log(n/k))
=O(nlog(n/k)
do sort list B[i] with quick sort