forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSleepSort.js
More file actions
25 lines (24 loc) · 737 Bytes
/
SleepSort.js
File metadata and controls
25 lines (24 loc) · 737 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
* This is a JavaScript implementation of the sleep sort algorithm.
* In general, sleep sort works by starting a separate task for
* each item to be sorted, where each task sleeps for an interval
* corresponding to the item's sort key, then emits the item.
* Items are then collected sequentially in time.
*
* Rosetta Code: https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
*/
export function sleepSort (items) {
const result = [];
for (let n of items) {
setTimeout(
() => {
result.push(n);
if (this.length === result.length) {
console.log(result);
}
},
n + 1
);
}
return result;
}