/utils

Bucket Sort

Spread the keys over buckets by value range, sort each small bucket, and join the buckets. Linear on average for evenly spread keys.

SolvesSorting

best
O(n)
average
O(n)
worst
O(n^2)
space
O(n)

Bucket sort cuts the key range into equal intervals. A key goes to the bucket of its interval. Buckets are ordered, so only the keys inside one bucket still need sorting.

Evenly spread keys: each of the 4 buckets gets 2 values, already in order. Sorting a bucket costs one comparison per value: O(n).

30121302413554685776907
1def bucket_sort(a):2    size = 253    buckets = [[] for _ in range(4)]4    for x in a:5        buckets[x // size].append(x)6    result = []7    for bucket in buckets:8        # insertion sort inside one bucket9        for i in range(1, len(bucket)):10            key = bucket[i]11            j = i - 112            while j >= 0 and bucket[j] > key:13                bucket[j + 1] = bucket[j]14                j = j - 115            bucket[j + 1] = key16        for x in bucket:17            result.append(x)18    return result
1 / 29

3 // 25 = 0: add it to bucket 0.

comparisons
0
shifts
0

How it works

This page uses integer keys in [0,100)[0, 100) and 4 buckets of width 25 [1].

  1. Put every key x into bucket x // 25.
  2. Sort each bucket with insertion sort. It is fast on short lists and stable.
  3. Append the buckets from the first to the last.

Complexity

CaseInputTime
Bestevenly spread keysO(n)O(n)
Averageuniformly random keysO(n)O(n)
Worstall keys in one bucketO(n2)O(n^2)

The linear bounds assume about nn buckets. Then a bucket holds one key on average, so the inner sorts cost O(n)O(n) in total. If the keys cluster, one bucket gets most of them and the inner sort dominates.

This demo keeps 4 buckets so the buckets stay visible. With a fixed bucket count, each bucket gets about n/4n/4 keys and the average is O(n2)O(n^2) again.

Implementations

  • Standard: 4 buckets of width 25, insertion sort per bucket. Real code uses about nn buckets of width range/n\text{range}/n.

Pitfalls

  • The key range must be known. Here a key outside [0,100)[0, 100) would index a missing bucket.
  • Skewed keys defeat it. Bucket sort has the quadratic worst case of its inner sort.
  • Use a stable inner sort, or equal keys can change order.

Related

References

  1. T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.

Further reading

  • K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.

Full bibliography