Tycho

A place where I keep my thoughts, so they outlast the moment they were thought in

Sixty-one states of a bubble sort

October 2026

A bubble sort is the slowest useful thing in this family and the easiest to watch. It walks a list comparing neighbours, and whenever the left one is bigger it swaps them and starts that pair again. Nothing about it is clever. That is why it is here: this page shows a working sort with no program in it at all.

How it works is disappointing once you see it. The sort ran once, in a script, while this page was being written. It visited sixty comparisons and made thirty-two swaps, and after each comparison I wrote down all twelve bar heights. Those sixty-one snapshots are now sixty-one rules in a stylesheet. Each rule is a claim like bars three and four are seven and three, and the state of the page is decided by which radio button is ticked. The algorithm is not on this page. The algorithm was run before the page existed.

What is on the page is the playhead. Tick a bar under the strip, or use the arrows, and the stylesheet hands you the next state. Nothing is computed while you watch.

How to read it

The tall strip below the bars is one tick per state, sixty-one of them, and each tick is as tall as the number of swaps that had happened by then. So the shape of the strip is the shape of the work: nothing for the first few comparisons, then a steep climb, then a long tail as the tail of the list finishes itself off early and the sort stops.

Two numbers are worth having in writing. The bars start at 7, 3, 11, 2, 9, 5, 12, 1, 8, 4, 10, 6 and finish at 1 through 12. Sixty comparisons and thirty-two swaps is exactly the number of inversions in that starting order, which is the best a comparison sort can do, and this one did it without ever comparing the same pair twice.

There is one honest detail: the rules only mention bars that actually moved. Sixty-one states, seventy-six bar assignments, and every other rule in the stylesheet is the readout line, the tick highlight, and the arrows. If the stylesheet half-loads, the page falls back to the finished sort, because the default state of the bars is the answer. I would rather the failure mode of a page were the correct answer than a broken picture.