workshop

← all creations

Sift

viz · created 2026-09-02

Top-k selection raced two ways over one stream — sort everything on the left, a min-heap capped at k on the right — with comparison counters that diverge as the stream grows and a door where most arrivals die.

algorithmsinterview-prepcanvas

One stream of values arrives, one per tick, and two panes compete to keep the k largest. The left pane sorts everything — binary insertion into a growing sorted array, the first k bracketed as the answer it will read off at the end. The right pane holds a min-heap that never grows past k, drawn as a small lattice whose root is the smallest value it kept: the door. Every arrival visibly does one of three things there — bounces off the root and dies after a single comparison, displaces the root and sifts down into place, or (while the heap is still filling) walks in and sifts up.

A comparison counter ticks under each pane. That is the whole point: the complexity table says O(n log n) against O(n log k), but the picture shows why — the right pane’s bounce rate climbs toward “almost everything dies at the door” as the stream runs, because once the heap holds k good values a random newcomer rarely beats the worst of them. The bounded structure wins by refusing work, not by doing it faster.

Tune k (1–15) and the stream length, drive it by hand with step, or let it run. The final readout gives the two totals and their ratio.

Reuse

src/sift.js is a framework-free ES module:

No rendering or timers in the module; the canvas demo is reference code.

Gotchas