sort.cny.shStart a race
Back to library
14 / 18Algorithm

Sleep Sort

Just for fun: each value naps proportionally, then wakes up in order.

StableIn-placeUnstable
BestO(n + max)
AverageO(n + max)
Worstdepends on the OS scheduler
01How it works

For every value, spawn a thread that sleeps for a duration proportional to that value, then appends itself to the output. Smaller values wake first, so the output emerges in order. The sorting is done by the operating system, not by the algorithm.

02Best for

Demos and party tricks — the gag of "sorting via setTimeout" never gets old. Also a memorable way to introduce the idea that timing is a side channel that can carry information.

03Avoid when

Anywhere a real result is needed. Accuracy is at the mercy of the scheduler, ties are racy, negative numbers don't work, and the runtime is bounded below by the largest value.