Bucket Sort

Drop each value into a bucket chosen by its value, count or digit, then read the buckets in order. No two values are compared, so it beats the O(n log n) floor when keys are small integers, evenly spread, or counts.

Overview

The idea

A comparison sort learns the order only by asking which of two values is bigger, and no such sort can beat O(n log n) in the worst case. Bucket sort skips the question. It computes a bucket index straight from the value, drops the value in, and reads the buckets back in order. Values in the same bucket are sorted separately, usually with a small comparison sort.

So every bucket sort runs in three moves.

  • Scatter: compute each value's bucket index, f(value), and drop the value into one of the buckets 0 to k - 1.
  • Sort: sort the values inside each bucket.
  • Gather: read the buckets in order.

The bucket index comes from the value itself, so no two values are ever compared across buckets.

The bucket function is the whole design. Four choices cover the common problems.

  • Bucket by value range: the index is the value times k divided by the range. This is bucket sort proper, and it fits when the values are spread evenly over a known range.
  • Bucket by exact value: one bucket per possible value. This is counting sort, and it fits when the keys are integers in a small range.
  • Bucket by one digit at a time, least significant first: this is radix sort, and it fits when the keys are integers or fixed-length strings with many digits.
  • Bucket by how often a value occurs: the index is its count. These are frequency buckets, and they fit when you need the most or least frequent items.

Its cost is O(n + k) on average for n values and k buckets when the values spread evenly. When they all land in one bucket the inner sort does all the work, and the worst case is that sort's cost, O(n²) with insertion sort. So the first question to ask is how the values are spread. The sections below take the four bucket functions in turn, starting with the value range.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio