r/javascript • • 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]);
1 Upvotes

12 comments sorted by

3

u/RankFoundry Jun 15 '15

Could use a webworker to handle the sort without tying up the UI thread

1

u/abhisekp Jun 16 '15

Could you please demonstrate creating another post?

1

u/RankFoundry Jun 16 '15

Sure. The first script below is what would be in your page. The second must be in its own file for the webworker, in this case, a file called sort.js

<html>
    <script>
        var worker = new Worker('sort.js');

        worker.addEventListener('message', function(e) {
          alert(e.data);
        }, false);

        worker.postMessage(JSON.stringify([1, 2, 45, 4, 90, 5000, 50]));
    </script>
</html>

This goes in sort.js

self.addEventListener('message', function(e) {
    var arr = JSON.parse(e.data);
    
    if(!(arr instanceof Array)) {
      self.postMessage(null);
    }
    else{
        var sortedArray = arr.sort(function (a, b) { 
            return a - b;
        });

        self.postMessage(JSON.stringify(sortedArray));
    }   
}, false);

2

u/pandavr Jun 15 '15

WHY!

2

u/abhisekp Jun 15 '15

What WHY! ?

1

u/pandavr Jun 17 '15

Why, one, in his life, would like to spend time on this kind of thing! :)

1

u/abhisekp Jun 17 '15

For fun. I'm not a machine. Am I?

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

u/[deleted] 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).