DrawCode Algorithm Visualizer • Sorting • Medium

Bucket Sort

Tags: Sorting, Distribution, Average Case, Floating Point

1. One-Liner

Bucket Sort maps each value to a bucket index, sorts inside small buckets, then concatenates buckets in order.


2. The Problem It Solves

For inputs uniformly spread across an interval (often [0,1) floats), average time can be O(n) with a simple bucketing map plus a tiny sort per bucket.


3. The Core Idea

Throw socks into labeled laundry bins by size range, sort each bin quickly, then empty bins 1, 2, 3… in order.


4. How It Works (Step-by-Step)

StepWhat Happens
1.Create n empty buckets (common choice)
2.Map each x to bucket ⌊n · normalize(x)⌋ (clamped)
3.Sort each bucket (insertion sort)
4.Concatenate buckets

5. Dry Run Example

Uniform keys in [0,1): bucket boundaries split [0,0.25), [0.25,0.5), …; after per-bucket sort, concatenate → sorted.


6. Key Properties

PropertyValue
AverageO(n) under uniform input assumptions
WorstO() if all keys land in one bucket
StableDepends on bucket sort choice

7. Where It Is Used

Company / SystemHow They Use It
Graphics / histogramsBinning + order
External toolsWhen distribution is known near-uniform

8. Interview Tips

State assumptions clearly; contrast worst case with Merge; mention map to index formula.


9. Comparison with Other Algorithms

AlgorithmAverageWorstNeeds
BucketO(n)O()Good spread
CountingO(n+k)O(n+k)Small integer range

10. Complexity

MetricValue
Time (Best)O(n + k) (bucket overhead)
Time (Average)O(n) uniform, O(n) buckets
Time (Worst)O()
SpaceO(n + k) buckets
Stable?Can be (with stable bucket sort)

Implementation Example (PYTHON)

def bucket_sort(arr):
    if not arr:
        return arr
    n = len(arr)
    lo, hi = min(arr), max(arr)
    if lo == hi:
        return arr
    buckets = [[] for _ in range(n)]
    for x in arr:
        i = int((x - lo) / (hi - lo) * (n - 1))
        buckets[i].append(x)
    out = []
    for b in buckets:
        b.sort()
        out.extend(b)
    return out

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer