Bucket Sort
- Ω( n + k )
- Θ( n + k )
- O( n2 )
- space O( n + k )
This bucket sort treats each value as an address. It finds the maximum, deals every element into one of about √n buckets using arithmetic on the value, runs insertion sort inside each bucket, and copies the result back. When values are spread evenly the buckets stay short and the work stays well below quadratic. When they pile up, one bucket does nearly all of the sorting.
- Comparisons count only element-against-element checks; loop and index checks are never counted.
- Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
- A swap counts once, as a swap. It is never also counted as a read or a write.
- Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.
How bucket sort works
For 5, 2, 6, 1, 4, 3 the first pass is a scan for the maximum: five comparisons, answer 6. With n = 6 the code uses ceil(√6) = 3 buckets, and a value v goes to bucket floor(v × 3 / 7), where 7 is the maximum plus one. That sends 2 and 1 to bucket 0, 4 and 3 to bucket 1, and 5 and 6 to bucket 2. Inside a bucket the elements keep their input order, so bucket 0 holds 2 then 1, bucket 1 holds 4 then 3, and bucket 2 holds 5 then 6.
None of that touches the visible array. Counting how many elements each bucket receives, turning those counts into start offsets and placing every element all happen in auxiliary buffers, which is why the table has nothing to show for the first stretch of the run. Insertion sort then repairs the buckets one at a time: it shifts 2 past 1 in bucket 0, shifts 4 past 3 in bucket 1, and finds 5 and 6 already in order. That costs three comparisons, bringing the total for this input to eight.
Only the final copy writes to the main array, and that is what the table records: six writes, left to right. After the first write the array reads 1, 2, 6, 1, 4, 3, with the 1 landing on top of the 5. That is safe because every original value already sits in the buffer. The second write stores a 2 over a 2 and changes nothing. The next writes give 1, 2, 3, 1, 4, 3, then 1, 2, 3, 4, 4, 3, then 1, 2, 3, 4, 5, 3, and the last one finishes at 1, 2, 3, 4, 5, 6. The repeated values in the intermediate rows are old contents waiting to be overwritten, not a bug.
| Step | Change | Array after |
|---|---|---|
| 1 | Write 1 at index 0 | 1 2 6 1 4 3 |
| 2 | Write 2 at index 1 | 1 2 6 1 4 3 |
| 3 | Write 3 at index 2 | 1 2 3 1 4 3 |
| 4 | Write 4 at index 3 | 1 2 3 4 4 3 |
| 5 | Write 5 at index 4 | 1 2 3 4 5 3 |
| 6 | Write 6 at index 5 | 1 2 3 4 5 6 |
All 6 changes are shown.
Pseudocode
max = largest value in a
k = ceil(sqrt(n))
create k empty buckets
for each x in a
append x to bucket floor(x * k / (max + 1))
for each bucket, in order
insertion-sort the bucket
append its elements to a
Why these complexities
Two things set the cost: the passes that touch every element a fixed number of times, and the insertion sorts inside the buckets. The first part is O(n + k) with k = ceil(√n). It reads the input to count, reads it again to place, walks the k offsets, and spends n - 1 comparisons finding the maximum. Space is also n + k, because the code keeps an n-element item buffer plus two small tables of k + 1 and k entries.
The insertion part is where the displayed average needs a caveat. The n + k shown for the average is the textbook bound, and its linear expected time assumes roughly as many buckets as elements, so each bucket holds a value or two. This implementation keeps the bucket count at √n to save memory, so on uniformly random data each bucket holds about √n values, and insertion sort on a bucket of size s costs roughly s² / 4 comparisons. Summed over √n buckets that is about n^1.5 / 4. A run on 1000 uniform random values measured about 9,500 comparisons here, consistent with that estimate plus the 999 spent on the maximum and far above n. So on uniform data this code really costs O(n^1.5) comparisons; the n + k figure describes only the distribution work, not the bucket sorting.
The worst case is n². Suppose one huge value stretches the range so that 199 small values all map to bucket 0: that bucket is sorted by insertion sort alone, and in reverse order it costs about s² / 2 comparisons. The best case, n + k, is real: on sorted input each bucket's insertion sort makes about one comparison per element, so only the linear counting, placement and copy-back passes remain. 1000 sorted values cost 1,967 comparisons against about 9,500 for shuffled ones, which is why the sort counts as adaptive.
Measured on this site
Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.
| Input | Comparisons | Writes | Swaps |
|---|---|---|---|
| Random | 85 | 195 | 0 |
| Already sorted | 57 | 140 | 0 |
| Reversed | 101 | 236 | 0 |
| Few distinct values | 59 | 140 | 0 |
When to use it
Use it when the values are spread fairly evenly over a known range, such as random numbers between 0 and 1. It can then sort in close to linear time.
Frequently asked questions
What makes bucket sort slow?
Clustered data. If most elements fall in one bucket, that bucket is sorted by insertion sort and the total approaches O(n²).
Why are there so many reads and writes?
Elements are moved into buckets and back using arithmetic on their values, not comparisons, so the buffer traffic is counted as reads and writes.
Is bucket sort stable?
It is stable when the elements are distributed in order and each bucket is sorted with a stable sort, such as insertion sort.
What does one extreme value do to the buckets?
The bucket index is computed from the maximum, so a single large value stretches the range and squeezes all the others into the first few buckets. With 199 values below 200 and one value of 10,000, every small value lands in bucket 0 and the run degrades to an insertion sort of almost the whole array. Bucket sort divides the value range evenly, not the elements, so it is sensitive to the shape of the data in a way that quick sort or merge sort is not.
Why use √n buckets rather than n?
More buckets mean shorter insertion sorts but a larger offset table and more bookkeeping reads and writes. With n buckets the sorting phase becomes nearly free on uniform data, yet the auxiliary space roughly triples and the code behaves like counting sort. With one bucket the whole thing is a plain insertion sort. The square root is a middle setting that keeps the extra memory small while still cutting each insertion sort down to a few dozen elements for arrays of this size.
Background
Dealing items into pigeonholes by a key and then sorting the small piles is far older than computers. Clerks sorted mail, library cards and punched cards this way, so there is no single inventor. In the computing literature the idea shows up as address calculation sorting, described by Isaac and Singleton in 1956, and Knuth discusses it in volume 3 of The Art of Computer Programming.
Counting sort and radix sort can be read as special cases: counting sort uses one bucket per value, radix sort buckets on one digit at a time. The classroom version in Cormen et al. assumes input drawn uniformly from the interval from 0 to 1, and that assumption is what justifies the linear expected time. Real data rarely arrives so conveniently, which is why bucket sort appears more often as a building block in specialised sorters than as a general library routine.
References
- Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, section 8.4 (Bucket sort)
- Isaac, Singleton, Sorting by address calculation, Journal of the ACM, 1956
Compare with
| Algorithm | Average time | Worst time |
|---|---|---|
| Counting Sort | Θ( n + k ) | O( n + k ) |
| Radix Sort | Θ( d(n + b) ) | O( d(n + b) ) |
| Best time | Ω( n + k ) | good |
|---|---|---|
| Average time | Θ( n + k ) | good |
| Worst time | O( n2 ) | poor |
| Worst space | O( n + k ) | fair |
Properties
- Stable
- Yes
- In place
- No
- Adaptive
- Yes
- Comparison-based
- No