3.6.8Sorting & Searching

Bucket sort — uniform distributions

1,681 words8 min readdifficulty · medium2 backlinks

WHAT it is

The assumption that makes it fast: inputs are drawn from a uniform distribution over a known interval, so buckets fill evenly.


WHY it works — derive the expected time from scratch

We want the expected total cost. The scatter, concatenation, and bucket creation are each O(n)O(n). The only risky part is sorting the buckets, since insertion sort on a bucket of size mm costs O(m2)O(m^2).

Let nin_i = number of elements landing in bucket ii. Total sort cost: T=O(n)+i=0n1O(ni2)T = O(n) + \sum_{i=0}^{n-1} O(n_i^2)

Take expectation: E[T]=O(n)+i=0n1O(E[ni2])E[T] = O(n) + \sum_{i=0}^{n-1} O\big(E[n_i^2]\big)

Now we need E[ni2]E[n_i^2]. Each of the nn elements lands in bucket ii independently with probability p=1/np = 1/n (uniform input → equal chance per bucket). So niBinomial(n,1/n)n_i \sim \text{Binomial}(n, 1/n).

Using the identity E[X2]=Var(X)+(E[X])2E[X^2]=\operatorname{Var}(X)+\big(E[X]\big)^2: E[ni2]=np(1p)+(np)2E[n_i^2] = np(1-p) + (np)^2

Plug p=1/np = 1/n: E[ni2]=n1n(11n)+(n1n)2=(11n)+1=21nE[n_i^2] = n\cdot\frac{1}{n}\left(1-\frac{1}{n}\right) + \left(n\cdot\frac1n\right)^2 = \left(1-\frac1n\right) + 1 = 2 - \frac1n

Why this is the punchline: E[ni2]E[n_i^2] is a constant (<2<2), not growing with nn. So: E[T]=O(n)+i=0n1O ⁣(21n)=O(n)+O(n)=O(n)E[T] = O(n) + \sum_{i=0}^{n-1} O\!\left(2-\frac1n\right) = O(n) + O(n) = \boxed{O(n)}


Figure — Bucket sort — uniform distributions

HOW to implement it

def bucket_sort(a):           # a: list of floats in [0, 1)
    n = len(a)
    buckets = [[] for _ in range(n)]      # n empty buckets
    for x in a:
        buckets[int(n * x)].append(x)     # scatter: index = floor(n*x)
    out = []
    for b in buckets:
        b.sort()                          # insertion sort in practice
        out.extend(b)                     # concatenate in order
    return out

Why int(n*x)? Stretching [0,1)[0,1) by nn maps the value directly to a bucket address, so equal-width slots correspond to equal value-ranges.


When it FAILS (the steel-man)


Recall Feynman: explain to a 12-year-old

Imagine 100 kids, each with a number from 0 to 99 written on a card, and you must line them up smallest to largest. Instead of comparing cards one by one, you put up 100 labeled boxes (0,1,2,...). Each kid drops their card in the box matching their number's first digits. Because the numbers are spread out evenly, almost every box gets just one card. Then you read the boxes left to right — done! The trick: the number tells you where to go, so you barely sort at all.


Recall checkpoint

Bucket sort: which input distribution gives expected O(n)O(n)?
A uniform distribution over a known range (so buckets fill evenly).
Bucket sort: formula for bucket index of value x[0,1)x\in[0,1) with nn buckets?
nx\lfloor n\cdot x\rfloor.
Bucket sort: worst-case time and when it happens?
O(n2)O(n^2), when all elements fall into one bucket (skewed/adversarial input).
Why doesn't the comparison-sort lower bound Ω(nlogn)\Omega(n\log n) apply to bucket sort?
The scatter step uses the value as an address (not comparisons), so it isn't a comparison sort.
For niBinomial(n,1/n)n_i\sim\text{Binomial}(n,1/n), what is E[ni2]E[n_i^2]?
21/n2 - 1/n (a constant <2<2), which is why total sort work is O(n)O(n).
What identity links E[X2]E[X^2], variance and mean?
E[X2]=Var(X)+(E[X])2E[X^2]=\operatorname{Var}(X)+(E[X])^2.
Roughly how many buckets should you use, and why?
About nn — one per expected element; many fewer causes collisions, many more wastes time on empty buckets.
How do you bucket-sort values in [lo,hi)[lo,hi) instead of [0,1)[0,1)?
Index =n(xlo)/(hilo)=\lfloor n\,(x-lo)/(hi-lo)\rfloor (normalize first).
Is bucket sort stable?
Yes, if each bucket's internal sort is stable and elements keep insertion order.

Connections

Concept Map

enables even fill

index = floor n times x

sort each bucket

concatenate in order

count per bucket

E X2 = Var + mean squared

constant per bucket

not comparison-based

beats

Uniform input in 0,1

Scatter into n buckets

About one item per bucket

Insertion sort

Sorted array

n_i ~ Binomial n, 1/n

E of n_i squared = 2 - 1/n

Expected time O n

Omega n log n does not apply

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Bucket sort ka funda simple hai: agar tumhara data uniformly spread hai ek known range mein (maan lo [0,1)[0,1)), toh range ko nn barabar tukdo (buckets) mein kaat do. Har value ko uske address ke hisaab se seedha bucket mein daal do — index nikalo nx\lfloor n\cdot x\rfloor. Kyunki data evenly faila hua hai, har bucket mein average sirf ek element aata hai. Phir har chhote bucket ko insertion sort se sort karo (bahut sasta, kyunki size 1-2 hi hota hai), aur saare buckets ko order mein jod do — sorted array ready!

Speed ka raaz: yeh comparison sort nahi hai scatter step mein. Value khud bata rahi hai ki kahan jaana hai, isliye Ω(nlogn)\Omega(n\log n) wali limit yahan lागू nahi hoti. Maths se: nin_i (ek bucket mein items) Binomial(n,1/n)(n, 1/n) hai, aur E[ni2]=21/nE[n_i^2] = 2 - 1/n — yeh constant hai, nn ke saath nahi badhta. Isliye total kaam O(n)+n×O(constant)=O(n)O(n) + n\times O(\text{constant}) = O(n). Bas yahi proof yaad rakhna.

Lekin dhyaan se: yeh O(n)O(n) sirf tab milta hai jab data uniform ho. Agar saare numbers ek hi bucket mein clump ho gaye (skewed data), toh ek bucket mein nn elements aa jayenge aur insertion sort O(n2)O(n^2) ho jayega. Toh interview mein bolना: "average case O(n)O(n) under uniform assumption, worst case O(n2)O(n^2)." Aur ek chhota bug se bacho — agar x=1.0x=1.0 aa gaya toh index nn ban jata hai jo out of range hai, isliye min(idx, n-1) clamp kar do ya range half-open [0,1)[0,1) rakho.

Go deeper — visual, from zero

Test yourself — Sorting & Searching

Connections