Bucket Sort and Its Expected Running Time
Counting sort and radix sort are fast because they assume something about the keys: small integers, or a fixed number of digits. Bucket sort assumes something different: that the keys are spread out evenly. If real numbers are drawn independently and uniformly from , bucket sort sorts them in expected time. It splits the interval into equal buckets, drops each number into its bucket, sorts the buckets (which are tiny on average) and concatenates them.
Unlike the analyses of randomized quicksort, the randomness here is in the input, not the algorithm. If the assumption fails, for instance if all the numbers fall in one bucket, bucket sort is as slow as the sort it uses inside each bucket.
The algorithm
BUCKET-SORT(a) // a[0..n-1] holds numbers in [0, 1)
1 B = n empty lists B[0], ..., B[n-1]
2 for each x in a
3 append x to B[floor(n * x)] // bucket i covers [i/n, (i+1)/n)
4 for i = 0 to n - 1
5 INSERTION-SORT(B[i])
6 return B[0] followed by B[1], ..., B[n-1]Correctness is quick. Take two numbers . If they are in different buckets, 's bucket index is at most 's, and it is strictly smaller since they differ, so comes first in the concatenation. If they are in the same bucket, insertion sort puts them in order. And because insertion sort is stable and line 3 appends in input order, equal keys keep their order: bucket sort is stable.
def insertion_sort(b):
for i in range(1, len(b)):
key, j = b[i], i - 1
while j >= 0 and b[j] > key:
b[j + 1] = b[j]; j -= 1
b[j + 1] = key
def bucket_sort(a, trace=False):
n = len(a)
buckets = [[] for _ in range(n)]
for x in a:
buckets[int(n * x)].append(x)
for i, b in enumerate(buckets):
insertion_sort(b)
if trace and b:
print(f"bucket {i} [{i / n:.1f}, {(i + 1) / n:.1f}): {b}")
return [x for b in buckets for x in b]
a = [0.42, 0.17, 0.93, 0.48, 0.05, 0.71, 0.26, 0.44, 0.12, 0.66]
print(bucket_sort(a, trace=True))bucket 0 [0.0, 0.1): [0.05]
bucket 1 [0.1, 0.2): [0.12, 0.17]
bucket 2 [0.2, 0.3): [0.26]
bucket 4 [0.4, 0.5): [0.42, 0.44, 0.48]
bucket 6 [0.6, 0.7): [0.66]
bucket 7 [0.7, 0.8): [0.71]
bucket 9 [0.9, 1.0): [0.93]
[0.05, 0.12, 0.17, 0.26, 0.42, 0.44, 0.48, 0.66, 0.71, 0.93]
With 10 numbers and 10 buckets, bucket 4 got three numbers, bucket 1 two, five buckets one each, and three stayed empty. Even on this small example, the buckets are uneven; the analysis shows how uneven they are on average and why it does not matter.
In C++
The same algorithm with std::vector buckets. The input is generated from a fixed-seed std::mt19937 as rng() / 2^32, which is exactly reproducible.
#include <algorithm>
#include <cstdio>
#include <random>
#include <vector>
void insertion_sort(std::vector<double>& b) {
for (std::size_t i = 1; i < b.size(); ++i) {
double key = b[i];
std::size_t j = i;
while (j > 0 && b[j - 1] > key) { b[j] = b[j - 1]; --j; }
b[j] = key;
}
}
std::vector<double> bucket_sort(const std::vector<double>& a) {
std::size_t n = a.size();
std::vector<std::vector<double>> buckets(n);
for (double x : a) buckets[static_cast<std::size_t>(n * x)].push_back(x);
std::vector<double> out;
for (auto& b : buckets) {
insertion_sort(b);
out.insert(out.end(), b.begin(), b.end());
}
return out;
}
int main() {
std::mt19937 rng(42);
std::vector<double> a(12);
for (double& x : a) x = rng() / 4294967296.0; // uniform in [0, 1)
std::vector<double> s = bucket_sort(a);
for (std::size_t i = 0; i < s.size(); ++i) std::printf(i ? " %.3f" : "%.3f", s[i]);
std::printf("\nsorted: %s\n", std::is_sorted(s.begin(), s.end()) ? "yes" : "no");
}0.100 0.156 0.156 0.183 0.375 0.446 0.597 0.599 0.732 0.780 0.797 0.951
sorted: yes
Expected running time
Everything except line 5 takes time. Let be the number of keys in bucket . Insertion sort on elements takes time, so
by linearity of expectation. The question is the expected square of a bucket's size. Its expected size is 1 (there are keys and equally likely buckets), but is not .
Use indicators, as in Indicator Random Variables: let , so and . Then
Here the product of two indicators needs independence, which the input assumption supplies (in the foundations course only sums of indicators appeared, which need none). So
The conclusion holds more generally: bucket sort runs in expected linear time whenever the sum of the squares of the bucket sizes is linear in expectation, for example when keys come from any distribution whose density is bounded, with buckets of equal probability.
Checking the analysis
The program estimates and counts the comparisons insertion sort makes in the buckets, for uniform input and for a skewed input that crowds everything into the first tenth of the interval.
import random
def bucket_stats(a):
n = len(a)
buckets = [[] for _ in range(n)]
for x in a:
buckets[int(n * x)].append(x)
comparisons = 0
for b in buckets:
for i in range(1, len(b)):
key, j = b[i], i - 1
while j >= 0:
comparisons += 1
if b[j] <= key: break
b[j + 1] = b[j]; j -= 1
b[j + 1] = key
out = [x for b in buckets for x in b]
assert out == sorted(a)
return sum(len(b) ** 2 for b in buckets), comparisons
rng = random.Random(21)
trials = 20
for n in [1000, 2000, 4000]:
sq = cmp = 0
for _ in range(trials):
s, c = bucket_stats([rng.random() for _ in range(n)])
sq += s; cmp += c
print(f"uniform n = {n}: mean sum of n_i^2 = {sq / trials:7.1f} (2n - 1 = {2 * n - 1}), "
f"comparisons {cmp / trials:6.0f} = {cmp / trials / n:.2f} n")
for n in [1000, 2000]:
s, c = bucket_stats([rng.random() / 10 for _ in range(n)])
print(f" skewed n = {n}: sum of n_i^2 = {s}, comparisons {c} = {c / n:.1f} n")uniform n = 1000: mean sum of n_i^2 = 1993.0 (2n - 1 = 1999), comparisons 452 = 0.45 n
uniform n = 2000: mean sum of n_i^2 = 4006.9 (2n - 1 = 3999), comparisons 908 = 0.45 n
uniform n = 4000: mean sum of n_i^2 = 7974.1 (2n - 1 = 7999), comparisons 1802 = 0.45 n
skewed n = 1000: sum of n_i^2 = 11030, comparisons 3317 = 3.3 n
skewed n = 2000: sum of n_i^2 = 21764, comparisons 6455 = 3.2 n
On uniform input the sum of squares lands right on and the comparisons are a constant times . When every key falls into the first tenth, each of those buckets holds about 10 keys: the sum of squares is about 5 times larger and the comparisons per key jump from under 0.5 to over 3. The cost is still linear here, because the crowding is a constant factor, but it is the crowding that sets the cost. In the extreme, all keys in one bucket, the cost is insertion sort's . A safer implementation sorts large buckets with an sort, which caps the worst case at without changing the expected linear time.
Where bucket sort fits
| needs | time | in place | stable | |
|---|---|---|---|---|
| counting sort | integer keys | no | yes | |
| radix sort | keys with digits in base | no | yes | |
| bucket sort | keys spread evenly over a known range | expected | no | yes (with a stable bucket sort) |
Bucket sort is the idea behind distribution sorts used for large data sets and in external sorting: split the keys into ranges that each fit in memory, sort each range, concatenate. The difficulty in practice is choosing the ranges so that they come out even, which is usually done by sampling the input first.
Test yourself
Why is and not ?
- Because buckets are sorted
- Because , and the bucket size has variance
- Because there are buckets
- It is 1; the formula is wrong
What is bucket sort's worst-case running time with insertion sort in the buckets?
The analysis of uses for . What justifies it?
- Linearity of expectation
- The keys are independent, so the events "key in bucket " and "key in bucket " are independent
- Insertion sort is stable
- The buckets have equal width