function sleepSort(array: number[]): Promise<number[]> {const output: number[] = [];
for (const value of array) { setTimeout(() => {output.push(value);
}, value);
}
return new Promise((resolve) => setTimeout(() => resolve(output), Math.max(...array) + 1));
}
12 values. Sleep sort starts one timer per value that sleeps that many milliseconds; whoever wakes first is printed first, so the output comes out sorted.
Understanding Sleep sort
The idea
Sleep sort starts one thread, or one timer, per value, and each one sleeps for as many milliseconds as its value before printing it. The smallest value wakes first, the largest last, and the printed sequence is sorted. Not a single comparison appears in the code.
The trick is that the comparisons did not disappear: the operating system keeps sleeping timers in a priority queue ordered by wake-up time, so it is the scheduler that sorts, in O(n log n), while the program waits for as long as the largest value. It is a joke with a lesson about where work hides.
The four stages
Complexity
Versus its siblings
Pseudocode
SLEEPSORT(array)
for each value in array
start a timer that, after value milliseconds, appends value to the output
wait until the last timer fires; return the output
When to use
Pitfalls
History
Sleep sort was posted anonymously on 4chan's programming board in January 2011 as a shell one-liner that spawned a background sleep per argument. It spread as a joke, then as an interview question about where the hidden O(n log n) lives.