Created
November 29, 2016 18:08
-
-
Save danrouse/ab8453977690ca37113d66324b7e48ef to your computer and use it in GitHub Desktop.
sleep sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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