Bucket sort
medium 15 minBucket sort splits the value range into equal buckets, drops each value into its bucket with floor(x · k), sorts each small bucket and reads the buckets out in order.
See it run
Drop each value into the bucket for its range, sort the small buckets, then read them out left to right.
Operations
Sort 7 decimals
Sort [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51] with 7 buckets. [x] marks the value being placed; each row below the input is one bucket.
Step 1 of 15
Seven values in [0, 1)
input
- 0.420
- 0.321
- 0.232
- 0.523
- 0.254
- 0.475
- 0.516
B0 [0, .143)
- —0
B1 [.143, .286)
- —0
B2 [.286, .429)
- —0
B3 [.429, .571)
- —0
B4 to B6 [.571, 1)
- —0
Every value lies in [0, 1), so we can split that range into equal slices. With n = 7 values we make k = 7 buckets, each \frac{1}{7} \approx 0.143 wide.
Step 1: Seven values in [0, 1)
def bucket_sort(arr): n = len(arr) buckets = [[] for _ in range(n)] # n empty buckets for x in arr: # 1. distribute idx = min(int(x * n), n - 1) # bucket for x; clamp x = 1.0 buckets[idx].append(x) for b in buckets: # 2. sort each bucket insertion_sort(b) out = [] for b in buckets: # 3. concatenate in order out.extend(b) return outdef 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] = keyprint(bucket_sort([0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51]))# [0.23, 0.25, 0.32, 0.42, 0.47, 0.51, 0.52]- Time
- O(n + k) average
- Space
- O(n + k)
- inside buckets
- 5 comparisons, 3 shifts
- plain insertion sort
- 12 comparisons, 8 shifts
Distribute, sort, concatenate. The buckets do the coarse ordering for free; the inner sort only tidies a few values each.
In the real world
The same bucket sort doing real jobs. Pick one and step through it.
A postal worker tosses letters into bins by the first digit of the ZIP code, sorts each bin, then stacks the bins in order.
Step 1 of 4
A pile of unsorted letters
pile
- 302100
- 100441
- 205172
- 100033
- 301014
- 200015
bin 1xxxx
- —0
bin 2xxxx
- —0
bin 3xxxx
- —0
Six letters arrive: 30210, 10044, 20517, 10003, 30101, 20001. Sorting the whole pile at once means comparing every letter with many others.
Step 1: A pile of unsorted letters
letters = [30210, 10044, 20517, 10003, 30101, 20001]bins = {1: [], 2: [], 3: []}for z in letters: bins[z // 10000].append(z) # first digit picks the binout = []for d in (1, 2, 3): out += sorted(bins[d]) # each bin is smallprint(out) # [10003, 10044, 20001, 20517, 30101, 30210]Common mistakes
The bugs interviewers watch for, with the fix beside each.
Index out of range for x = 1.0
criticalint(1.0 * n) is n, one past the last bucket. Any input that can reach the top of the range must be clamped into the last bucket.
Wrongidx = int(x * n)buckets[idx].append(x) # IndexError when x == 1.0Rightidx = min(int(x * n), n - 1)buckets[idx].append(x)Using x * n on data outside [0, 1)
criticalThe formula assumes values in [0, 1). For 42.0 it gives a huge index; for a negative value Python silently indexes from the end. Normalise with the minimum and maximum first.
Wrongidx = int(x * n) # x = 42.0 or -3.5Rightlo, hi = min(arr), max(arr)span = (hi - lo) or 1idx = min(int((x - lo) / span * n), n - 1)Creating buckets with [[]] * n
critical[[]] * n makes n references to the same list, so every append goes into every bucket. Build a fresh list per bucket.
Wrongbuckets = [[]] * n # one list, n namesRightbuckets = [[] for _ in range(n)]Forgetting to sort inside the buckets
majorDistribution only orders values between buckets. Inside a bucket they stay in arrival order, so [0.42, 0.32] would be copied out unsorted.
Wrongreturn [x for b in buckets for x in b]Rightfor b in buckets: b.sort()return [x for b in buckets for x in b]Using round() instead of floor
majorround(0.42 * 4) is 2 but 0.42 belongs to bucket 1. Rounding shifts the ranges by half a bucket, mixing values out of order across buckets and overflowing the last one.
Wrongidx = round(x * k)Rightidx = min(int(x * k), k - 1) # int() floors non-negative valuesTrusting it on skewed data
minorIf most values fall into a few buckets, those buckets become large and insertion sort inside them goes quadratic. Use an O(n log n) inner sort, or just the built-in sort, when the distribution is unknown.
Wronginsertion_sort(bucket) # bucket may hold most of the inputRightbucket.sort() # Timsort: O(m log m) per bucket
Interview tips
How to explain it
- Split the value range into k equal buckets, drop each value into its bucket with floor(x · k), sort each bucket, and concatenate.
- Average O(n + k) when the data is uniform, because each bucket holds about one value.
- Worst case O(n²) when everything lands in one bucket and insertion sort is used inside.
- O(n + k) extra space; stable if the inner sort is stable.
Spot it in the wild
- Floats spread evenly over a known range, like random numbers in [0, 1).
- Group by frequency or by score band before picking the top few.
- Maximum gap between sorted neighbours in linear time.
Memory tricks
- DISC: Distribute, Insert by index, Sort each bucket, Concatenate.
- Mail room: bins by ZIP, sort each bin, stack the bins.
- Uniform in, linear out. Clustered in, quadratic out.
Watch out
- Clamp the index: min(int(x * k), k - 1).
- Normalise data that is not in [0, 1).
- Build buckets with a comprehension, never [[]] * n.