AlgoViz

Bucket sort

medium 15 min

Bucket 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

0:00 / 5:28

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.

Step 1 of 3

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 kk empty lists. For values in [0,1)[0, 1), bucket ii covers [ik,i+1k)[\frac{i}{k}, \frac{i+1}{k}).

  • Distribute

    Put each value xx in bucket ⌊x⋅k⌋\lfloor x \cdot k \rfloor. 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

Two linear passes (distribute and concatenate) around a sorting phase that is cheap when buckets are small.
Python
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]
The textbook version: k=nk = n buckets, insertion sort inside each.
Edit and run it in your browser
DISC: the four beats
  1. 1DistributeValues into buckets
  2. 2InsertBy the index formula
  3. 3SortEach bucket on its own
  4. 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)

idx(x)=min⁡(⌊x⋅k⌋, k−1),bucket i=[ik, i+1k)\text{idx}(x) = \min\left(\lfloor x \cdot k \rfloor,\ k - 1\right), \qquad \text{bucket } i = \left[\tfrac{i}{k},\ \tfrac{i+1}{k}\right)
The floor picks the slice; the min⁡\min only matters for x=1.0x = 1.0, which would otherwise land in a bucket that does not exist. For other ranges, normalise first: x′=x−min⁡max⁡−min⁡x' = \frac{x - \min}{\max - \min}.
xx⋅7x \cdot 7⌊x⋅7⌋\lfloor x \cdot 7 \rfloorBucket range
0.422.942[0.286,0.429)[0.286, 0.429)
0.322.242[0.286,0.429)[0.286, 0.429)
0.231.611[0.143,0.286)[0.143, 0.286)
0.523.643[0.429,0.571)[0.429, 0.571)
0.251.751[0.143,0.286)[0.143, 0.286)
0.473.293[0.429,0.571)[0.429, 0.571)
0.513.573[0.429,0.571)[0.429, 0.571)
Seven values, seven buckets of width 17≈0.143\frac{1}{7} \approx 0.143. Note 0.42 sits just below 37≈0.4286\frac{3}{7} \approx 0.4286, so it belongs to bucket 2.

Computing a safe index

Normalise, floor, clamp. Skipping any of the three is the most common bucket sort bug.

Worked example

Sorting seven decimals

  1. 1

    Create 7 buckets

    For [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51], n=7n = 7, so k=7k = 7 buckets of width 17\frac{1}{7}.

  2. 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. 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. 4

    Concatenate

    B0 + B1 + B2 + B3 + B4 + B5 + B6 = [0.23, 0.25, 0.32, 0.42, 0.47, 0.51, 0.52].

BucketAfter distributeAfter sortComparisonsShifts
B10.23, 0.250.23, 0.2510
B20.42, 0.320.32, 0.4211
B30.52, 0.47, 0.510.47, 0.51, 0.5232
total53
Plain insertion sort on the same 7 values needs 12 comparisons and 8 shifts. The buckets only ever compare values that are close together.

Correctness

Why concatenation gives sorted output

The bucket index is a non-decreasing function of the value: a bigger xx 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

x∈Bi, y∈Bj, i<j ⟹ x<i+1k≤jk≤y ⟹ x<yx \in B_i,\ y \in B_j,\ i < j \ \Longrightarrow\ x < \tfrac{i+1}{k} \le \tfrac{j}{k} \le y \ \Longrightarrow\ x < y
Every value of an earlier bucket is below the lower edge of every later bucket. Sorted buckets joined in index order are therefore sorted overall.

Two kinds of order

Distribution handles the coarse order for free; the inner sort handles the fine order.

Complexity

Average case: O(n + k)

Distribution touches each value once (O(n)O(n)), creating and scanning the buckets costs O(k)O(k), and concatenation is O(n+k)O(n + k). The only question is how expensive the inner sorts are. If nin_i values land in bucket ii, insertion sort costs O(ni2)O(n_i^2) there.

Expected cost of the inner sorts, k = n

E[ni2]=Var⁡(ni)+E[ni]2=n⋅1n(1−1n)+1=2−1n\mathbb{E}[n_i^2] = \operatorname{Var}(n_i) + \mathbb{E}[n_i]^2 = n \cdot \tfrac{1}{n}\left(1 - \tfrac{1}{n}\right) + 1 = 2 - \tfrac{1}{n}
With uniform input each value picks a bucket with probability 1n\frac{1}{n}, so nin_i is binomial with mean 1. Summing over nn buckets: ∑iE[ni2]=2n−1=O(n)\sum_i \mathbb{E}[n_i^2] = 2n - 1 = O(n).

Total

T(n)=O(n)⏟distribute+O(k)⏟buckets+O(n)⏟sort, expected+O(n+k)⏟concatenate=O(n+k)T(n) = \underbrace{O(n)}_{\text{distribute}} + \underbrace{O(k)}_{\text{buckets}} + \underbrace{O(n)}_{\text{sort, expected}} + \underbrace{O(n + k)}_{\text{concatenate}} = O(n + k)
With k=nk = n this is O(n)O(n) expected time: linear, faster than the Ω(nlog⁡n)\Omega(n \log n) bound that limits comparison sorts. The bound does not apply because the index formula reads the value directly instead of comparing.

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 k=5k = 5: every ⌊x⋅5⌋\lfloor x \cdot 5 \rfloor is 2, so one bucket holds all nn values and bucket sort turns into plain insertion sort on the whole input.

One overloaded bucket

n2=n ⟹ shifts≤∑i=1n−1i=n(n−1)2=O(n2)n_2 = n \ \Longrightarrow\ \text{shifts} \le \sum_{i=1}^{n-1} i = \frac{n(n-1)}{2} = O(n^2)
That cluster happens to arrive sorted, so it costs only 4 comparisons and 0 shifts. Reversed, [0.45, 0.44, 0.43, 0.42, 0.41] costs the full 5⋅42=10\frac{5 \cdot 4}{2} = 10 shifts.

How the spread decides the cost

Swapping insertion sort for merge sort or the built-in sort inside each bucket caps the worst case at O(nlog⁡n)O(n \log n).

Tuning

Choosing k, and the space cost

Expected shifts with k buckets

E[shifts]=k⋅E[ni(ni−1)]4=k⋅n(n−1)/k24=n(n−1)4k\mathbb{E}[\text{shifts}] = k \cdot \frac{\mathbb{E}[n_i(n_i - 1)]}{4} = k \cdot \frac{n(n-1)/k^2}{4} = \frac{n(n-1)}{4k}
A bucket of mm random values has m(m−1)4\frac{m(m-1)}{4} inversions on average, and insertion sort shifts once per inversion. More buckets divide the inner work.
k (n = 1000)Average bucketExpected shiftsExtra space
11000249,750O(n)O(n)
1010024,975O(n)O(n)
10010about 2,498O(n)O(n)
10001about 250O(n+k)O(n + k)
k=1k = 1 is just insertion sort. k=nk = n makes the inner work linear. Going far beyond nn only adds empty buckets to create and scan.

Properties

  • Stable when the inner sort is stable and values are appended in input order.
  • Average O(n+k)O(n + k), best O(n+k)O(n + k).
  • Works with floats, where counting sort cannot.
  • Buckets can be sorted in parallel or on separate machines.

Costs

  • Not in place: O(n+k)O(n + k) extra space for the buckets.
  • Worst case O(n2)O(n^2) 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

PropertyBucket sortCounting sortRadix sort
Average timeO(n+k)O(n + k)O(n+k)O(n + k)O(d(n+b))O(d(n + b))
Worst timeO(n2)O(n^2)O(n+k)O(n + k)O(d(n+b))O(d(n + b))
Extra spaceO(n+k)O(n + k)O(n+k)O(n + k)O(n+b)O(n + b)
StableYes, with a stable inner sortYesYes
Groups byvalue rangeexact valueone digit at a time
Data it needsuniform values, known rangesmall integer rangefixed-width keys
Typical usefloats in [0,1)[0, 1)ages, gradesphone numbers, IDs
kk is the number of buckets or possible values, dd the number of digits, bb the digit base. Counting sort is bucket sort with one bucket per value; radix sort runs a stable bucket pass per digit.

Which sort?

Linear-time sorts all trade generality for speed. When in doubt, the built-in O(nlog⁡n)O(n \log n) sort is the safe choice.

Variants

Beyond floats in [0, 1)

  • Any numeric range

    Normalise with x−min⁡max⁡−min⁡\frac{x - \min}{\max - \min}, then bucket as usual. Guard against max⁡=min⁡\max = \min.

  • Integer bands

    Scores 0 to 100 into bands with score // 25. One bucket per value turns it into counting sort.

  • Bucket by frequency

    Top kk frequent items: bucket cc holds the values seen cc times, then read from the top. O(n)O(n).

  • External sorting

    Data too big for memory: write each bucket to its own file, sort the files one at a time, then append them.

Python
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]
General version: any numbers, kk buckets, built-in sort inside so the worst case stays O(nlog⁡n)O(n \log n).
Edit and run it in your browser

Pigeonhole trick: maximum gap

Buckets solve the classic maximum gap problem in O(n)O(n) without fully sorting anything.

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 O(n)O(n) 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 O(n+k)O(n + k) 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 [0,1)[0, 1), sensor readings spread over a fixed scale.

  • Group then rank

    Top kk frequent words, scores into grade bands, prices into ranges.

  • Gaps between neighbours

    Maximum gap in sorted order, closest values within a distance tt.

Recap

Key takeaways

Key points

  • Bucket sort: create kk buckets, drop each value in bucket ⌊x⋅k⌋\lfloor x \cdot k \rfloor, sort each bucket, concatenate.
  • Clamp the index with min⁡(⋅,k−1)\min(\cdot, k - 1) and normalise data that is not in [0,1)[0, 1).
  • Average and best case O(n+k)O(n + k) on uniform data, because each bucket holds about one value (∑E[ni2]=2n−1\sum \mathbb{E}[n_i^2] = 2n - 1).
  • Worst case O(n2)O(n^2) when everything lands in one bucket; an O(nlog⁡n)O(n \log n) inner sort caps it at O(nlog⁡n)O(n \log n).
  • O(n+k)O(n + k) 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.

Sources