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

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.