Created
May 6, 2015 06:56
-
-
Save raymonstah/af4cb8323afb3878c50d to your computer and use it in GitHub Desktop.
Sleep Sort in JavaScript (No Threads!)
This file contains hidden or 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
// Raymond Ho | |
// JavaScript makes Sleep Sort so easy to implement.. | |
// Exponentially slower if sorting larger numbers. | |
function sleepNumber(number) { | |
// The timeout is (n^2) so that close numbers are no longer close. | |
// Example: 1 is really close to 2, but 1^2 isn't close to 2^2. | |
setTimeout(function(){ | |
console.log(number); | |
}, number*number); | |
} | |
function sleepSort(array) { | |
for (i = 0; i < array.length; ++i){ | |
sleepNumber(array[i]); | |
} | |
} | |
// Generate 100 random numbers for sorting. | |
randoms = []; | |
for (i = 0; i < 100; ++i) { | |
// Random number between 1 - 100 | |
randomInt = Math.floor((Math.random()*100) + 1); | |
randoms.push(randomInt); | |
} | |
// Sort said random numbers. | |
sleepSort(randoms); | |
Interesting! I didn't know Bun has a sleep
API
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typescript/Bun implementation: