Skip to content

Instantly share code, notes, and snippets.

@benslv
Created February 16, 2021 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benslv/5d684a916312316b604e214433290da3 to your computer and use it in GitHub Desktop.
Save benslv/5d684a916312316b604e214433290da3 to your computer and use it in GitHub Desktop.
An O(max(array)) sorting algorithm...
const sleepSort = async (arr) => {
const sorted = [];
const max = Math.max(...arr);
const min = Math.min(...arr);
for (let item of arr) {
setTimeout(() => sorted.push(item), item - min);
}
await new Promise((resolve) => setTimeout(resolve, max));
return sorted;
};
// Example
let arr = [20, 5, 100, 1, 90, 200, 40, 29];
sleepSort(arr).then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment