Sleep Sort: The O(wtf) Asynchronous Sorting Algorithm
Description
A screenshot of a tweet from the 'JavaScript Daily' Twitter account (@JavaScriptDaily). The tweet text reads: 'Presenting the "sleep sort", our favorite O(wtf) sorting algorithm. (C'mon, it's the weekend..)'. Below this is a dark-themed code block with a JavaScript snippet commented as '// sleep sort'. The code initializes an array `numbers = [8, 42, 38, 111, 2, 39, 1];` and then iterates over it, calling `setTimeout` for each number, with the number itself as the delay. The callback function for the timeout is `console.log(num)`. A watermark for 't.me/dev_meme' is visible at the bottom. The meme explains 'sleep sort,' a notoriously impractical sorting algorithm that works by exploiting asynchronous timers. For each number in the input array, it sets a timeout equal to the number's value. The JavaScript event loop then ensures that the callbacks (which print the numbers) execute in ascending order of their timeout duration. It's a joke about finding clever but absurd solutions, and its 'O(wtf)' complexity label perfectly captures its status as a piece of programming folklore rather than a serious algorithm
Comments
7Comment deleted
Sleep sort is the only algorithm where its performance is directly proportional to the magnitude of the input values. It's also the only one that can be DDoS'd by the number 2147483647
Sleep sort: where the runtime caps at 2³¹-1 ms, because by the time setTimeout overflows the business requirements will have pivoted twice
Sleep sort: the only algorithm where "it works on my machine" depends on your CPU load, and the correctness proof requires a discussion about whether JavaScript timers respect the principle of causality
Sleep sort: the only algorithm where performance degrades linearly with your dataset's maximum value, and where sorting [1, 2, 1000000] means you're committed to waiting 16 minutes for results. It's technically O(n + max(array)) time complexity, but we prefer O(wtf) because it more accurately captures the architectural review committee's reaction when you propose using setTimeout delays as a comparison function in production
Sleep sort in JS: outsourcing compare() to setTimeout - works until GC pauses, timer clamping, and the 2^31−1 ms cap remind you you’re benchmarking the event loop, not a sorting algorithm
Sleep sort: Outsourcing complexity to JS's event loop, because why merge when you can just nap your way to sorted?
Sleep sort: converting sorting into O(max(input)) wall-clock and delegating correctness to timer jitter - enterprise-grade O(wtf)