Bucket Sort
Bucket Sort
Bucket Sort
Bucket Sort
Bucket sort assumes that the input is generated by a random
process and drawn from a uniform distribution.
In other words the elements are distributed uniformly and
independently over the interval [0,1].
Bucket sort divides the interval [0,1] into n equal sized
subintervals or buckets. Then distributes the n inputs into
these buckets.
After that the elements of each buckets are sorted using a
sorting algorithm generally using insertion or quick sort.
Finally the buckets are concatenated together in order.
Consider that the input is an n-element array A and each
element A[i] in the array satisfies the 0<=A[i]<1
Bucket Sort Algorithm
Bucket-Sort(A)
1. Let B[0….n-1] be a new array
2. n = length[A]
3. for i = 0 to n-1
4. make B[i] an empty list
5. for i = 1 to n
6. do insert A[i] into list B[ n A[i] ]
7. for i = 0 to n-1
8. do sort list B[i] with Insertion-Sort
9. Concatenate lists B[0], B[1],…,B[n-1] together in
order
Bucket
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .21
Bucket: Loop 1
n=6
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .21
0 1 2 3 4 5
B
Bucket: Loop 2
FOR n=6, i=1
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .21
B[ n A[i] ] = B[ 6X.74 ]=B[ 4.44 ]=B[4]
0 1 2 3 4 5
B
Bucket: Loop 2
FOR n=6, i=2
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .21
.74
0 1 2 3 4 5
B
Bucket: Loop 2
FOR n=6, i=3
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .21
.74
.17
0 1 2 3 4 5
B
Bucket: Loop 2
FOR n=6, i=4
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .21
.26 .74
.17
0 1 2 3 4 5
B
Bucket: Loop 2
FOR n=6, i=5
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .21
B[ n A[i] ] = B[ 6X.39 ]=B[ 2.34 ]=B[2]
.26 .74
.17 .72
0 1 2 3 4 5
B
Bucket: Loop 2
FOR n=6, i=6
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .94
.26 .74
.17 .39
.72
0 1 2 3 4 5
B
Bucket: End of Loop 2
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .94
.26 .74
.39 .94
.17 .72
0 1 2 3 4 5
B
Bucket: Loop 3
Apply insertion sort
on each bucket
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .94
0 1 2 3 4 5
B
Bucket
Concatenate the
buckets in order
1 2 3 4 5 6
A .74 .17 .26 .72 .39 .94
Sorted output
0 1 2 3 4 5
B .17 .26 .39 .72 .74 .94
0 1 2 3 4 5
B
Example - Bucket Sort
A 1 .78 B 0 /
5 .72 4 / Distribute
6 .94 5 / Into buckets
7 .21 6 .68 /
9 .23 8 /
10 .68 9 .94 /
Example - Bucket Sort
0 /
1 .12 .17 /
3 .39 /
Sort within each
4 /
bucket
5 /
6 .68 /
7 .72 .78 /
8 /
9 .94 /
Example - Bucket Sort
.12 .17 .21 .23 .26 .39 .68 .72 .78 .94 /
Analysis of Bucket Sort
Bucket-Sort(A)
1. Let B[0….n-1] be a new array
2. n = length[A]
3. for i = 0 to n-1
4. make B[i] an empty list Step 5 and 6
5. for i = 1 to n takes O(n)
time
6. do insert A[i] into list B[ floor of n A[i] ]
Step 7 and 8
7. for i = 0 to n-1 takes O(n
8. do sort list B[i] with Insertion-Sort log(n/k) time