Bucket sort

Split into buckets and sort each one · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Bucket sort

Bucket sort is a sort that isn't based on comparing everything with everything. It splits the data into k ordered buckets, each with a range of values. For example, numbers between 0 and 1 into 10 buckets: 0 to 0.1, 0.1 to 0.2, and so on. Then it sorts each bucket separately, with any algorithm, and finally joins them in order, from the smallest bucket to the largest.

If the data spreads evenly, each of the k buckets gets about n/k elements. Sorting them costs O(n log(n/k)) in total, and with many buckets, n/k is small and the cost approaches O(n + k), almost linear. It uses O(n + k) extra memory: the k buckets and the n elements inside them. It's stable if the algorithm sorting each bucket is stable.

Bucket sort's problem is spreading evenly, because real data usually isn't uniformly distributed. If almost everything lands in the same bucket, that bucket is almost the whole array and nothing was gained. One fix is to split overly full buckets again into smaller buckets, recursively, until they all have roughly the same count.

If you know how the data is spread, you can choose the bucket boundaries so they end up even. For example, if prices follow a curve where most are near the average, the middle buckets are made narrower and the ones at the ends wider. That way each bucket gets roughly the same count even though the ranges differ.

Bucket sort is very useful for data that doesn't fit in memory. If 1 billion records on disk must be sorted and memory only holds 1 million at a time, they're split into 1,000 bucket files by range, each file is loaded and sorted separately, and they're joined in order. Each step fits in memory.

Bucket sort and counting sort are cousins. Counting sort is a bucket sort where each bucket has a single possible value: one bucket for 0, another for 1, another for 2. Since everything in a bucket is equal, there's no need to sort inside, counting is enough. Bucket sort, on the other hand, puts a range in each bucket and does need to sort inside.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Split into buckets and sort each one