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.
Video lesson · Chapter 1 of 6
The post office bins
Bucket sort — The neon mail chutes
1:27Reel
Read caption
Bo sorts numbered neon envelopes through four range chutes, then orders the envelopes inside each compartment. Route by range. Sort each pile. Read left to right.
How it works
Step through the idea, or press Play.
Distribute. Drop each value into the bucket for its range: index floor(x · k)
Understand it
Start here
What bucket sort is
Bucket sort is a distribution sort. Instead of comparing every value with every other, it first throws each value into a bucket that covers one slice of the value range. Values in an earlier bucket are always smaller than values in a later one, so after a quick sort inside each bucket, reading the buckets left to right gives the sorted array.
Create buckets
Make empty lists. For values in , bucket covers .
Distribute
Put each value in bucket . One multiply, one floor, one append.
Sort buckets
Each bucket holds only a few values, so insertion sort finishes it fast.
Concatenate
Join the buckets in index order. Sorted buckets in sorted order make a sorted array.
The algorithm
Distribute, sort, concatenate
Bucket sort, end to end
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] = keydef bucket_sort(arr): n = len(arr) if n == 0: return [] buckets = [[] for _ in range(n)] # n empty buckets for x in arr: idx = min(int(x * n), n - 1) # clamp x = 1.0 into the last bucket buckets[idx].append(x) for b in buckets: insertion_sort(b) return [x for b in buckets for x in b] # concatenateprint(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]- 1DistributeValues into buckets
- 2InsertBy the index formula
- 3SortEach bucket on its own
- 4ConcatenateBuckets in order
Distribute, Insert by index, Sort each bucket, Concatenate.
The key formula
Which bucket does x go in?
Bucket index for x in [0, 1)
| x | Bucket range | ||
|---|---|---|---|
| 0.42 | 2.94 | 2 | |
| 0.32 | 2.24 | 2 | |
| 0.23 | 1.61 | 1 | |
| 0.52 | 3.64 | 3 | |
| 0.25 | 1.75 | 1 | |
| 0.47 | 3.29 | 3 | |
| 0.51 | 3.57 | 3 |
Computing a safe index
Worked example
Sorting seven decimals
- 1
Create 7 buckets
For
[0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51], , so buckets of width . - 2
Distribute
B1 gets
[0.23, 0.25], B2 gets[0.42, 0.32], B3 gets[0.52, 0.47, 0.51]. B0, B4, B5 and B6 stay empty. Values keep their arrival order inside a bucket. - 3
Sort each bucket
B1 is already sorted. B2 needs one shift:
[0.32, 0.42]. B3 needs two:[0.47, 0.51, 0.52]. - 4
Concatenate
B0 + B1 + B2 + B3 + B4 + B5 + B6 =
[0.23, 0.25, 0.32, 0.42, 0.47, 0.51, 0.52].
| Bucket | After distribute | After sort | Comparisons | Shifts |
|---|---|---|---|---|
| B1 | 0.23, 0.25 | 0.23, 0.25 | 1 | 0 |
| B2 | 0.42, 0.32 | 0.32, 0.42 | 1 | 1 |
| B3 | 0.52, 0.47, 0.51 | 0.47, 0.51, 0.52 | 3 | 2 |
| total | 5 | 3 |
Correctness
Why concatenation gives sorted output
The bucket index is a non-decreasing function of the value: a bigger never gets a smaller index. So if two values land in different buckets, the one in the lower bucket is the smaller one. The only disorder left is inside a bucket, and the inner sort removes it.
Order between buckets
Two kinds of order
Complexity
Average case: O(n + k)
Distribution touches each value once (), creating and scanning the buckets costs , and concatenation is . The only question is how expensive the inner sorts are. If values land in bucket , insertion sort costs there.
Expected cost of the inner sorts, k = n
Total
Complexity
Worst case: everything in one bucket
The average-case argument assumed uniform data. Take [0.41, 0.42, 0.43, 0.44, 0.45] with : every is 2, so one bucket holds all values and bucket sort turns into plain insertion sort on the whole input.
One overloaded bucket
[0.45, 0.44, 0.43, 0.42, 0.41] costs the full shifts.How the spread decides the cost
Tuning
Choosing k, and the space cost
Expected shifts with k buckets
| k (n = 1000) | Average bucket | Expected shifts | Extra space |
|---|---|---|---|
| 1 | 1000 | 249,750 | |
| 10 | 100 | 24,975 | |
| 100 | 10 | about 2,498 | |
| 1000 | 1 | about 250 |
Properties
- Stable when the inner sort is stable and values are appended in input order.
- Average , best .
- Works with floats, where counting sort cannot.
- Buckets can be sorted in parallel or on separate machines.
Costs
- Not in place: extra space for the buckets.
- Worst case with insertion sort inside.
- Needs a known range and a roughly uniform distribution.
- Not purely comparison-free: it still compares inside buckets.
Head to head
Bucket vs counting vs radix
| Property | Bucket sort | Counting sort | Radix sort |
|---|---|---|---|
| Average time | |||
| Worst time | |||
| Extra space | |||
| Stable | Yes, with a stable inner sort | Yes | Yes |
| Groups by | value range | exact value | one digit at a time |
| Data it needs | uniform values, known range | small integer range | fixed-width keys |
| Typical use | floats in | ages, grades | phone numbers, IDs |
Which sort?
Variants
Beyond floats in [0, 1)
Any numeric range
Normalise with , then bucket as usual. Guard against .
Integer bands
Scores 0 to 100 into bands with
score // 25. One bucket per value turns it into counting sort.Bucket by frequency
Top frequent items: bucket holds the values seen times, then read from the top. .
External sorting
Data too big for memory: write each bucket to its own file, sort the files one at a time, then append them.
def bucket_sort_range(nums, k=None): if len(nums) < 2: return list(nums) k = k or len(nums) lo, hi = min(nums), max(nums) span = (hi - lo) or 1 # all equal: avoid dividing by 0 buckets = [[] for _ in range(k)] for x in nums: idx = min(int((x - lo) / span * k), k - 1) buckets[idx].append(x) out = [] for b in buckets: out.extend(sorted(b)) # stable, O(m log m) return outprint(bucket_sort_range([29, -3, 14, 88, 51, 7, 62]))# [-3, 7, 14, 29, 51, 62, 88]Pigeonhole trick: maximum gap
Pattern spotting
When to reach for it
Good for
- Uniformly distributed data, such as random floats.
- Floating point numbers in a known range.
- Data that splits naturally into ranges or bands.
- External sorting, when the data is too large for memory.
- When an average time matters and the distribution is trusted.
Avoid when
- The data is skewed or clustered.
- The range is unknown and costly to find.
- Memory is tight: it needs extra space.
- Many values share the same small range.
- Keys are small integers: counting sort is simpler and never quadratic.
Uniform floats
Random numbers in , sensor readings spread over a fixed scale.
Group then rank
Top frequent words, scores into grade bands, prices into ranges.
Gaps between neighbours
Maximum gap in sorted order, closest values within a distance .
Recap
Key takeaways
Key points
- Bucket sort: create buckets, drop each value in bucket , sort each bucket, concatenate.
- Clamp the index with and normalise data that is not in .
- Average and best case on uniform data, because each bucket holds about one value ().
- Worst case when everything lands in one bucket; an inner sort caps it at .
- extra space, not in place; stable if the inner sort is stable.
- Counting sort buckets by exact value, radix sort by digit, bucket sort by range.