Skip to content

Instantly share code, notes, and snippets.

@danrouse
Created November 29, 2016 18:08
Show Gist options
  • Save danrouse/ab8453977690ca37113d66324b7e48ef to your computer and use it in GitHub Desktop.
Save danrouse/ab8453977690ca37113d66324b7e48ef to your computer and use it in GitHub Desktop.
sleep sort
function sleepSort(arr) {
var output = [];
for (var i = 0; i < arr.length; i++) {
setTimeout(output.push.bind(output, arr[i]), arr[i] * 100);
}
return output;
}
function populateArray(n) {
var arr = [];
for (var i = 0; i < n; i++) {
arr.push(Math.floor(Math.random() * 100));
}
return arr;
}
var arr = populateArray(100);
console.log('initial array', arr);
var sorted = sleepSort(arr);
var interval = setInterval(function() {
console.log('sorting array', sorted);
if (sorted.length === arr.length) {
clearInterval(interval);
console.log('done sorting!', sorted);
}
}, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment