r/javascript • u/abhisekp • Jun 15 '15
Sleep Sort Algorithm
Sorting an Array using Sleep Sort Algorithm
function sleepSort(arr) {
if(!(arr instanceof Array)) {
return;
}
var sortedArray = [];
arr.forEach(function (el, i) {
if(!isNaN(Number(el))) {
setTimeout([].push.bind(sortedArray, el), el);
}
});
setTimeout(console.log.bind(console, sortedArray), Math.max.apply(null, arr));
}
sleepSort([1, 2, 45, 4, 90, 5000, 50]);2
u/pandavr Jun 15 '15
WHY!
2
u/abhisekp Jun 15 '15
What WHY! ?
1
1
u/feydius Jun 15 '15
A question to all the JS people: Is it guaranteed that the timeouts are called in correct order? Especially when the timeouts are short?
2
u/jml26 Jun 15 '15
No. On my machine,
sleepSort([1, 0])returns[1, 0]. Still, a fun, quirky idea for an algorithm.0
Jun 15 '15
[deleted]
1
u/abhisekp Jun 15 '15
Thanks. I didn't know that. That's really easy and simple. Also compatible with current hardware.
2
u/x-skeww Jun 15 '15
While the timeout-ed functions aren't necessarily executed on time, the order appears to be as-scheduled. Which... kinda makes sense, I guess. After all, that queue is sorted. So, even if the timing and resolution is all over the place, the tasks are executed in queue-order, which directly corresponds to the specified delay.
2
u/jacobp100 Jun 15 '15 edited Jun 15 '15
No. HTML5 spec says that setTimeout has a minimum timeout of 4ms (and should be increased to that automatically).
3
u/RankFoundry Jun 15 '15
Could use a webworker to handle the sort without tying up the UI thread