From 5979279178af0b43b0b4415fbf0cd330d9cc66ff Mon Sep 17 00:00:00 2001 From: Sebastian-GOAT Date: Sat, 26 Sep 2026 20:00:13 +0200 Subject: [PATCH] feat: add sleepsort algorithm --- sorts/sleep_sort.ts | 43 +++++++++++++++++++++++++++++++++++ sorts/test/sleep_sort.test.ts | 15 ++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 sorts/sleep_sort.ts create mode 100644 sorts/test/sleep_sort.test.ts diff --git a/sorts/sleep_sort.ts b/sorts/sleep_sort.ts new file mode 100644 index 00000000..ca4f656a --- /dev/null +++ b/sorts/sleep_sort.ts @@ -0,0 +1,43 @@ +/** + * @function sleepSort + * @description For each n, sleep sort waits n milliseconds before pushing it to the result array. + * @Complexity_Analysis + * Space complexity - O(n) + * Each element requires its own thread or timer instance, + * which scales linearly with the size of the input array. + * + * Time complexity + * Best case - O(n + max(input)) + * Occurs when the OS schedules threads in linear time and + * the maximum value in the input array is very small. + * + * Worst case - unbounded + * Occurs when at least one of the numbers is infinitely or + * exponentially large, or when the system runs out of resources. + * + * Average case - O(n log n + max(input)) + * Occurs as the OS scheduler inserts the n wake-up timers into + * an internal priority queue (min-heap), followed by the time + * it takes for the maximum element to finish sleeping. + * + * @param {number[]} arr - The input array. + * @return {number[]} - The sorted array. + * @example sleepSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8] + */ +export async function sleepSort(arr: number[], scale = 10): Promise { + + if (arr.length < 2) return arr + + const result: number[] = [] + + const promises = arr.map(async num => { + return new Promise(resolve => setTimeout(() => { + result.push(num) + resolve() + }, num * scale)) // Multiply the number by some scaling variable so the order stays correct + }) + + await Promise.all(promises) + + return result +} diff --git a/sorts/test/sleep_sort.test.ts b/sorts/test/sleep_sort.test.ts new file mode 100644 index 00000000..e64535f8 --- /dev/null +++ b/sorts/test/sleep_sort.test.ts @@ -0,0 +1,15 @@ +import { sleepSort } from '../sleep_sort'; + +describe('SleepSort', () => { + test.each([ + { arr: [1], expectedResult: [1] }, + { arr: [2, 1], expectedResult: [1, 2] }, + { arr: [3, 1, 2], expectedResult: [1, 2, 3] }, + { arr: [3, 4, 1, 2], expectedResult: [1, 2, 3, 4] } + ])( + 'The return value of $arr should be $expectedResult', + async ({ arr, expectedResult }) => { + expect(await sleepSort(arr)).toStrictEqual(expectedResult); + } + ); +});