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 Jun 2, 2022

The real challenge is to implement it such that the function actually returns the array, instead of logging. This is my attempt:

'use strict';
(function(){
//static memory and delay multiplier
const M = [], mul = 2

globalThis.sleepSort = a => {
	let c = a.length
	while (a.length) {
		const v = a.pop()
		setTimeout(()=> M.push(v), v * mul)
	}
	while (M.length < c);
	const out = []
	while (M.length) out.push(M.pop())
	return out
}
})()

But it gets stuck in an infinite loop and I have no idea why lol

@Brendan-Stubbs
Copy link

Brendan-Stubbs commented Nov 10, 2022

The real challenge is to implement it such that the function actually returns the array, instead of logging. This is my attempt:

I came across this, and I had to give it a go :)

const sleepSort = async (arr) => {
  const result = [];

  await Promise.all(
    arr.map(async (n) => {
      await new Promise((res) => setTimeout(res, n));
      result.push(n);
    })
  );

  return result;
};

await sleepSort(sleepSort([11, 4, 1, 6, 3, 7, 9, 5]));

@Rudxain
Copy link

Rudxain commented Nov 11, 2022

@Brendan-Stubbs It works! but only if the duped call is removed. BTW, thank you! that code has helped me understand async programming better. I seriously need to spend more time learning about that subject.

Since I prefer self-commenting code, I would rewrite it as

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const sleepSort = async (arr) => {
  const out = [];

  await Promise.all(
    arr.map(async (n) => {
      await sleep(n);
      out.push(n);
    })
  );

  return out;
};

@hainsdominic
Copy link

Typescript/Bun implementation:

const sleepSort = async (arr: number[]) => {
  const result: number[] = [];

  await Promise.all(
    arr.map(async (n) => {
      await Bun.sleep(n);
      result.push(n);
    })
  );

  return result;
};

console.log(await sleepSort([11, 4, 1, 6, 3, 7, 9, 5]));

@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