We want the expected total cost. The scatter, concatenation, and bucket creation are each O(n). The only risky part is sorting the buckets, since insertion sort on a bucket of size m costs O(m2).
Let ni = number of elements landing in bucket i. Total sort cost:
T=O(n)+∑i=0n−1O(ni2)
Take expectation:
E[T]=O(n)+∑i=0n−1O(E[ni2])
Now we need E[ni2]. Each of the n elements lands in bucket i independently with probability p=1/n (uniform input → equal chance per bucket). So ni∼Binomial(n,1/n).
Using the identity E[X2]=Var(X)+(E[X])2:
E[ni2]=np(1−p)+(np)2
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) by n maps the value directly to a bucket address, so equal-width slots correspond to equal value-ranges.
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.
Bucket sort ka funda simple hai: agar tumhara data uniformly spread hai ek known range mein (maan lo [0,1)), toh range ko n barabar tukdo (buckets) mein kaat do. Har value ko uske address ke hisaab se seedha bucket mein daal do — index nikalo ⌊n⋅x⌋. 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) wali limit yahan lागू nahi hoti. Maths se: ni (ek bucket mein items) Binomial(n,1/n) hai, aur E[ni2]=2−1/n — yeh constant hai, n ke saath nahi badhta. Isliye total kaam O(n)+n×O(constant)=O(n). Bas yahi proof yaad rakhna.
Lekin dhyaan se: yeh 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 n elements aa jayenge aur insertion sort O(n2) ho jayega. Toh interview mein bolना: "average case O(n) under uniform assumption, worst case O(n2)." Aur ek chhota bug se bacho — agar x=1.0 aa gaya toh index n ban jata hai jo out of range hai, isliye min(idx, n-1) clamp kar do ya range half-open [0,1) rakho.