AlgoLab

O(n + k)·O(n + k) space·stable
645559896316373459948511843281951114277

Starting bucket sort on an array of 20 items, using 10 buckets.

Starting bucket sort on an array of 20 items, using 10 buckets.
  1. 1find the smallest and largest value, and divide that range evenly into a fixed number of buckets
  2. 2read the next value and place it into the bucket that covers its range
  3. 3once every value has been distributed, sort each bucket that holds more than one value
  4. 4within a bucket being sorted, compare the value being inserted with the one before it
  5. 5shift the larger value one place to the right to make room, or drop the value into the gap once nothing larger remains
  6. 6walk through the buckets in order, writing each bucket's sorted values back into the array
  7. 7the array is fully sorted
Comparisons
0
Writes
0
Accesses
0
Bucket updates
0

Complexity

BestO(n + k)
AverageO(n + k)
WorstO(n²)
Extra spaceO(n + k)
StableYes
n at n=20 predicts 20; this run took 0.

Bucket sort

Bucket sort divides the range from the smallest to the largest value into a fixed number of buckets, reads each value in turn and drops it into the bucket covering its range, sorts each bucket that ends up holding more than one item, then writes the buckets back into the array in order. Unlike counting sort, a bucket can hold many different values, so each one needs its own small sort rather than a simple count.

When it is the right choice

Bucket sort is a good choice when values are spread roughly evenly across a known range and a plain array cannot cheaply hold one slot per distinct value the way counting sort does. It degrades toward its O(n²) worst case when the values are badly clustered, since most of them then land in one bucket and that bucket's own sort dominates; on data like that, a comparison sort with a guaranteed O(n log n) bound is the safer choice.

How it works

Worth noticing

Cost

Best
O(n + k)
Average
O(n + k)
Worst
O(n²)
Extra space
O(n + k)
Stable
Yes

Worth comparing

All algorithms