TExcelTAD
Home › Sorting & Order Statistics › Bucket Sort and Its Expected Running Time

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 nn real numbers are drawn independently and uniformly from [0,1)[0, 1), bucket sort sorts them in expected Θ(n)\Theta(n) time. It splits the interval into nn 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

text
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 x≤yx \le y. If they are in different buckets, xx's bucket index ⌊nx⌋\lfloor nx \rfloor is at most yy's, and it is strictly smaller since they differ, so xx 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.

python · try it yourself
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.

cpp · try it yourself
#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 Θ(n)\Theta(n) time. Let nin_i be the number of keys in bucket ii. Insertion sort on nin_i elements takes O(ni2)O(n_i^2) time, so

T(n)=Θ(n)+∑i=0n−1O(ni2),E[T(n)]=Θ(n)+∑i=0n−1O(E[ni2])T(n) = \Theta(n) + \sum_{i=0}^{n-1} O(n_i^2), \qquad \mathbb{E}[T(n)] = \Theta(n) + \sum_{i=0}^{n-1} O\bigl(\mathbb{E}[n_i^2]\bigr)

by linearity of expectation. The question is the expected square of a bucket's size. Its expected size is 1 (there are nn keys and nn equally likely buckets), but E[ni2]\mathbb{E}[n_i^2] is not E[ni]2\mathbb{E}[n_i]^2.

Use indicators, as in Indicator Random Variables: let Xij=I{key j falls in bucket i}X_{ij} = I\{\text{key } j \text{ falls in bucket } i\}, so ni=∑jXijn_i = \sum_j X_{ij} and Pr⁡[Xij=1]=1n\Pr[X_{ij} = 1] = \frac{1}{n}. Then

E[ni2]=E[∑j∑kXijXik]=∑jE[Xij2]+∑j≠kE[XijXik]=n⋅1n+n(n−1)⋅1n2Xij2=Xij; keys j≠k independent=2−1n.\begin{aligned} \mathbb{E}[n_i^2] &= \mathbb{E}\Bigl[\sum_{j} \sum_{k} X_{ij} X_{ik}\Bigr] = \sum_{j} \mathbb{E}[X_{ij}^2] + \sum_{j \ne k} \mathbb{E}[X_{ij} X_{ik}] \\ &= n \cdot \frac{1}{n} + n(n-1) \cdot \frac{1}{n^2} && X_{ij}^2 = X_{ij};\ \text{keys } j \ne k \text{ independent} \\ &= 2 - \frac{1}{n}. \end{aligned}

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

E[T(n)]=Θ(n)+n⋅O(2−1n)=Θ(n).\mathbb{E}[T(n)] = \Theta(n) + n \cdot O\Bigl(2 - \frac{1}{n}\Bigr) = \Theta(n).

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 E[∑ini2]=n(2−1n)=2n−1\mathbb{E}\bigl[\sum_i n_i^2\bigr] = n\left(2 - \frac{1}{n}\right) = 2n - 1 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.

python · try it yourself
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 2n−12n - 1 and the comparisons are a constant times nn. 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 Θ(n2)\Theta(n^2). A safer implementation sorts large buckets with an O(nlg⁡n)O(n \lg n) sort, which caps the worst case at O(nlg⁡n)O(n \lg n) without changing the expected linear time.

Where bucket sort fits

needs time in place stable
counting sort integer keys 0..k0..k Θ(n+k)\Theta(n + k) no yes
radix sort keys with dd digits in base kk Θ(d(n+k))\Theta(d(n + k)) no yes
bucket sort keys spread evenly over a known range Θ(n)\Theta(n) 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 E[ni2]=2−1n\mathbb{E}[n_i^2] = 2 - \frac{1}{n} and not E[ni]2=1\mathbb{E}[n_i]^2 = 1?

  1. Because buckets are sorted
  2. Because E[X2]=E[X]2+Var⁡[X]\mathbb{E}[X^2] = \mathbb{E}[X]^2 + \operatorname{Var}[X], and the bucket size has variance 1−1n1 - \frac{1}{n}
  3. Because there are n−1n - 1 buckets
  4. It is 1; the formula is wrong

What is bucket sort's worst-case running time with insertion sort in the buckets?

  1. Θ(n)\Theta(n)
  2. Θ(nlg⁡n)\Theta(n \lg n)
  3. Θ(n2)\Theta(n^2)
  4. Θ(n3)\Theta(n^3)

The analysis of E[ni2]\mathbb{E}[n_i^2] uses E[XijXik]=1n2\mathbb{E}[X_{ij} X_{ik}] = \frac{1}{n^2} for j≠kj \ne k. What justifies it?

  1. Linearity of expectation
  2. The keys are independent, so the events "key jj in bucket ii" and "key kk in bucket ii" are independent
  3. Insertion sort is stable
  4. The buckets have equal width