Algorithms · Visualized
Bucket Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Bucket Sort scatters elements into a number of 'buckets' based on their value range, sorts each bucket individually (usually with insertion sort, since buckets are small), and then concatenates the buckets in order. Time: O(n + k) average, O(n²) — all elements land in one bucket worst; space: O(n + k).
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Bucket Sort
SortingBucket Sort scatters elements into a number of 'buckets' based on their value range, sorts each bucket individually (usually with insertion sort, since buckets are small), and then concatenates the buckets in order. It works best when the input is uniformly distributed over a range.
How Bucket Sort Works
- Create a fixed number of empty buckets, each responsible for a sub-range of the input's value range.
- Go through the input array and place each element into the bucket matching its value.
- Sort each individual bucket (a small, simple sort like insertion sort works well here).
- Concatenate all the buckets in order, from the bucket covering the smallest values to the one covering the largest.
- The concatenated result is the fully sorted array.
Bucket Sort Worked Example
Input: [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
With 10 buckets for ranges [0.0-0.1), [0.1-0.2), ... [0.9-1.0): 0.17,0.12→bucket1; 0.39,0.26,0.21,0.23→buckets 2&3; 0.78,0.72→bucket7; 0.94→bucket9; 0.68→bucket6. Sort each small bucket, then read buckets in order to get: [0.12,0.17,0.21,0.23,0.26,0.39,0.68,0.72,0.78,0.94].
def bucket_sort(a):
if not a:
return a
n = len(a)
lo, hi = min(a), max(a)
buckets = [[] for _ in range(n)]
for v in a:
b = (v - lo) * (n - 1) // (hi - lo)
buckets[b].append(v)
out = []
for b in buckets:
b.sort()
out.extend(b)
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Bucket Sort Time & Space Complexity
When to Use Bucket Sort
- Sorting floating-point numbers spread evenly across a range, e.g. [0, 1).
- Parallel sorting — since buckets are independent, they can be sorted on different threads/machines.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.