Skip to content

Instantly share code, notes, and snippets.

@raymonstah
Created May 6, 2015 06:56
Show Gist options
  • Save raymonstah/af4cb8323afb3878c50d to your computer and use it in GitHub Desktop.
Save raymonstah/af4cb8323afb3878c50d to your computer and use it in GitHub Desktop.
Sleep Sort in JavaScript (No Threads!)
// 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);
@Rudxain
Copy link

Rudxain commented Jan 1, 2024

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