This algorithm takes K seconds where K is the value of the greatest element.
This means if you just multiply everything by -1 it will take negative time to sort.
Then you can simply unmultiply and read from end to beginning from now on.
This is faster than having it presorted.
For better usage: you don’t need to write it into console. Just write it in an array!
finally, sorting in linear time /s
I know this under the name sleepSort.
I’m dumb, can someone ELI5 please?
The output is sorted due to the fact that for each number, a timer is started that prints out the number after waiting a number of milliseconds equal to said number.
Therefore, 1 is printed first after delaying for 1 millisecond, 5 is printed second after 5 milliseconds etc.
Perfectly explained, thank you!
Wait till you find out how the runtime manages multiple concurrent timers
it’s
while (true) { let t = Date.now(); if (timeoutMap.has(t)) timeoutMap[t](); }of course. Clearly O(n).
disclaimer
Feel free to use it. I guarantee it is bug free. Comes with express warranty. This notice is legally binding.
I found a way to optimize your code without affecting the result. By making it branchless, I was able to get my CPU to 100% utilization!




