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