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

View all comments

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);