Bucket Sort
Spread the keys over buckets by value range, sort each small bucket, and join the buckets. Linear on average for evenly spread keys.
SolvesSorting
- best
- O(n)
- average
- O(n)
- worst
- O(n^2)
- space
- O(n)
Bucket sort cuts the key range into equal intervals. A key goes to the bucket of its interval. Buckets are ordered, so only the keys inside one bucket still need sorting.
Evenly spread keys: each of the 4 buckets gets 2 values, already in order. Sorting a bucket costs one comparison per value: O(n).
- 0–243
- 25–49
- 50–74
- 75–99
1def bucket_sort(a):2 size = 253 buckets = [[] for _ in range(4)]4 for x in a:5 buckets[x // size].append(x)6 result = []7 for bucket in buckets:8 # insertion sort inside one bucket9 for i in range(1, len(bucket)):10 key = bucket[i]11 j = i - 112 while j >= 0 and bucket[j] > key:13 bucket[j + 1] = bucket[j]14 j = j - 115 bucket[j + 1] = key16 for x in bucket:17 result.append(x)18 return result3 // 25 = 0: add it to bucket 0.
- comparisons
- 0
- shifts
- 0
How it works
This page uses integer keys in and 4 buckets of width 25 [1].
- Put every key
xinto bucketx // 25. - Sort each bucket with insertion sort. It is fast on short lists and stable.
- Append the buckets from the first to the last.
Complexity
| Case | Input | Time |
|---|---|---|
| Best | evenly spread keys | |
| Average | uniformly random keys | |
| Worst | all keys in one bucket |
The linear bounds assume about buckets. Then a bucket holds one key on average, so the inner sorts cost in total. If the keys cluster, one bucket gets most of them and the inner sort dominates.
This demo keeps 4 buckets so the buckets stay visible. With a fixed bucket count, each bucket gets about keys and the average is again.
Implementations
- Standard: 4 buckets of width 25, insertion sort per bucket. Real code uses about buckets of width .
Pitfalls
- The key range must be known. Here a key outside would index a missing bucket.
- Skewed keys defeat it. Bucket sort has the quadratic worst case of its inner sort.
- Use a stable inner sort, or equal keys can change order.
Related
References
- T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.
Further reading
- K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.