|
| 1 | +/** |
| 2 | + * @function sleepSort |
| 3 | + * @description For each n, sleep sort waits n milliseconds before pushing it to the result array. |
| 4 | + * @Complexity_Analysis |
| 5 | + * Space complexity - O(n) |
| 6 | + * Each element requires its own thread or timer instance, |
| 7 | + * which scales linearly with the size of the input array. |
| 8 | + * |
| 9 | + * Time complexity |
| 10 | + * Best case - O(n + max(input)) |
| 11 | + * Occurs when the OS schedules threads in linear time and |
| 12 | + * the maximum value in the input array is very small. |
| 13 | + * |
| 14 | + * Worst case - unbounded |
| 15 | + * Occurs when at least one of the numbers is infinitely or |
| 16 | + * exponentially large, or when the system runs out of resources. |
| 17 | + * |
| 18 | + * Average case - O(n log n + max(input)) |
| 19 | + * Occurs as the OS scheduler inserts the n wake-up timers into |
| 20 | + * an internal priority queue (min-heap), followed by the time |
| 21 | + * it takes for the maximum element to finish sleeping. |
| 22 | + * |
| 23 | + * @param {number[]} arr - The input array. |
| 24 | + * @return {number[]} - The sorted array. |
| 25 | + * @example sleepSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8] |
| 26 | + */ |
| 27 | +export async function sleepSort(arr: number[], scale = 10): Promise<number[]> { |
| 28 | + |
| 29 | + if (arr.length < 2) return arr |
| 30 | + |
| 31 | + const result: number[] = [] |
| 32 | + |
| 33 | + const promises = arr.map(async num => { |
| 34 | + return new Promise<void>(resolve => setTimeout(() => { |
| 35 | + result.push(num) |
| 36 | + resolve() |
| 37 | + }, num * scale)) // Multiply the number by some scaling variable so the order stays correct |
| 38 | + }) |
| 39 | + |
| 40 | + await Promise.all(promises) |
| 41 | + |
| 42 | + return result |
| 43 | +} |
0 commit comments