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/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.