3.6.8 · D2Sorting & Searching

Visual walkthrough — Bucket sort — uniform distributions

2,528 words11 min readBack to topic

We are going to answer one question: how much total work does sorting the buckets cost, on average? Every step below builds one piece of that answer.


Step 1 — What a bucket even is (the number line, chopped)

WHAT. Imagine every input value is a point sitting on a ruler that runs from up to (but not touching) . We write this range as : the square bracket means " is included", the round bracket means " is not". We chop this ruler into equal-width pieces. Each piece is a bucket — a little box that will catch the points that land in its slice.

WHY. We chop into exactly pieces (where is how many numbers we have) because we are betting on one number per box. If that bet holds, sorting inside each box is trivial. Fewer boxes → crowded boxes → slow. Way more boxes → wasted empty boxes. So boxes is the balance point.

PICTURE. Look at figure s01. The ruler is split into equal slices. The width of each slice is — that is what "equal-width" means. A point sitting in the ruler falls into the slice numbered by how many full slices fit below it.

Figure — Bucket sort — uniform distributions

Step 2 — Scatter: the value is its own address

WHAT. Walk through the input once. For each value , compute and drop into that box. No comparing against other values — we just read where it belongs.

WHY. This is the whole secret of bucket sort. A comparison sort is forced to ask "is ?" many times, and that questioning cannot beat . Here we never ask that. We use the value itself as a postal address — the same trick Hashing uses. Because we skip comparisons at this stage, the wall does not apply to us.

PICTURE. In figure s02, arrows fly from each input value straight down into its box. Notice how the ten arrows spread out — most boxes catch one, a couple catch two or three, some catch nothing. That unevenness is exactly what the rest of the proof must measure.

Figure — Bucket sort — uniform distributions

Step 3 — The one risky cost: sorting inside a box

WHAT. After scattering, each box holds a small pile. We sort each pile with Insertion sort. Let be the number of items in box . Sorting a pile of size with insertion sort costs, in the worst case, about steps.

WHY ? Insertion sort compares each new item against the ones already placed. In the worst case, item number 2 does 1 comparison, item 3 does 2, and so on — that adds up to , which grows like the square of the pile size. This squaring is the danger: if one box swallows everything, and we are back to — slow.

PICTURE. Figure s03 shows two boxes side by side: a lonely box with 1 item (cost ) versus a crowded box with 4 items (cost ). The crowded box costs far more than four lonely boxes — that is the penalty of clumping we must bound.

Figure — Bucket sort — uniform distributions

Everything now hinges on: how big is on average?


Step 4 — Each item flips a coin: the Binomial appears

WHAT. Fix one box, say box . Each of the input values either lands in it or not. Because the input is drawn from a uniform distribution, every value is equally likely to hit any of the boxes. So the chance one value lands in box is

WHY this exact model? "Uniform" literally means no box is favoured. With equal-width slices covering the whole range, each slice grabs a share of the probability. And the values are drawn independently — one value's landing spot tells you nothing about the next. Independent coin flips, each with success chance , counted up, is precisely the Binomial distribution. So:

PICTURE. Figure s04 shows little coins, one per input value. Each coin lands "heads" (into box ) with probability . The number of heads is . The bar chart on the right is the shape of : a big spike at and , a small tail — most of the time you get or items, rarely more.

Figure — Bucket sort — uniform distributions

Step 5 — Mean and variance of one box's load

WHAT. Two facts about :

  • :: the average number of items in the box.
  • :: the spread — how much the load wobbles around that average. Big variance = boxes are lumpy (some empty, some crowded).

WHY these formulas. Since , its average is the sum of averages: . For variance, because the switches are independent, variances add. One switch has variance (a quick fact about a single 0/1 coin), and there are of them, giving .

PICTURE. Figure s05 plants the average as a yellow line and draws the variance as the width of the spread around it. Watch the two arrows: as grows the average pins to , and the spread narrows toward too — the box load stays "about one, give or take one."

Figure — Bucket sort — uniform distributions

Now plug in our specific :

Read that in plain words: on average exactly one item per box, wobbling by just under one. Exactly the picture we bet on in Step 1.


Step 6 — Turning mean+variance into

WHAT. The sort cost was , so we need the average of the square, — not the square of the average. These differ, and the gap between them is exactly the variance. For any random quantity — call the generic placeholder , and in a moment we set — the definition of variance rearranges to: Applying it with (our box load) gives exactly what we need:

WHY this identity. Variance is defined as "the average squared distance from the mean," . Rearranging gives the line above. We need it because clumping (variance) is precisely the extra cost that squaring exposes — the identity lets us pay for it explicitly.

PICTURE. Figure s06 stacks two blocks: a green block of height (the cost if boxes were perfectly even) and a red block of height (the extra cost that randomness/clumping adds). Their sum is the true expected square work.

Figure — Bucket sort — uniform distributions

The headline: , a constant. It does not grow with .


Step 7 — Summing over all boxes: the linear finish

WHAT. Take the honest cost from Step 3, , and average it. Two rules of expectation do all the work:

  • Linearity of expectation :: the average of a sum is the sum of the averages, even when the are not independent of each other. This is the rule that lets us slide the inside the , turning into . (We do not need independence between boxes — linearity holds regardless.)
  • The constant has no randomness, so its average is itself.

WHY it collapses. From Step 6, every , a fixed number. Substitute it: Both pieces are of the form "constant times " (plus a lower-order ), so Notice we only invoked big- at the very end, on an ordinary number — never inside an expectation.

PICTURE. Figure s07 lines up all boxes, each carrying its little constant cost bar (height ). The total is just short bars stacked — a straight line growing with , never bending upward. That straight line is linear time.

Figure — Bucket sort — uniform distributions

Step 8 — The degenerate case: what if the input is NOT uniform?

WHAT. Everything above rested on for every box. If the input is skewed or adversarial, that assumption dies. In the extreme, all values crash into one box: that box has , and insertion sort on it costs .

WHY it matters. The result is an average over uniform inputs, not a promise for every input. The proof's engine — "each box gets of the mass" — simply isn't true when data clumps. This is the same warning the parent note gives: spread evenly = speedy; clumped = crawls.

PICTURE. Figure s08 contrasts the two worlds: on the left, ten arrows fan out evenly (the dream); on the right, all ten arrows dive into a single box (the nightmare). Same algorithm, wildly different cost — decided entirely by the input's shape.

Figure — Bucket sort — uniform distributions

The one-picture summary

Figure s09 overlays the two forces that fight inside : the ideal even cost (a flat green baseline at , one unit per box) and the actual expected cost including clumping (a red curve landing at ). The gap between them — the variance term — never widens into a new power of ; it stays a constant multiple. That single picture is why the average total work is and not : clumping only ever doubles the baseline, it never squares it.

Figure — Bucket sort — uniform distributions
Recall Feynman retelling — the walkthrough in plain words

We laid a ruler from 0 to 1 and chopped it into equal boxes. Every number, instead of being compared, just walked to the box matching its own value — the value is its own address, so we dodged the comparison speed limit. Because the numbers were spread evenly, each box expected about one number. But randomness makes boxes lumpy — some get two, some get none. Sorting inside a box costs the square of its load, so lumpiness is what we feared. We modelled each box's load as counting heads in coin flips (a Binomial), found its average is and its wobble is just under , and combined them via : the average squared load is — a tiny constant. Then linearity of expectation let us add that constant across all boxes to get — a straight line, linear time. The one catch: if the numbers clump into a single box, the whole story collapses to . Even spread = fast; clumped = slow.


Recall checkpoint


Connections