Skip to content

Commit 5979279

Browse files
feat: add sleepsort algorithm
1 parent 19b4ced commit 5979279

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

‎sorts/sleep_sort.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

‎sorts/test/sleep_sort.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { sleepSort } from '../sleep_sort';
2+
3+
describe('SleepSort', () => {
4+
test.each([
5+
{ arr: [1], expectedResult: [1] },
6+
{ arr: [2, 1], expectedResult: [1, 2] },
7+
{ arr: [3, 1, 2], expectedResult: [1, 2, 3] },
8+
{ arr: [3, 4, 1, 2], expectedResult: [1, 2, 3, 4] }
9+
])(
10+
'The return value of $arr should be $expectedResult',
11+
async ({ arr, expectedResult }) => {
12+
expect(await sleepSort(arr)).toStrictEqual(expectedResult);
13+
}
14+
);
15+
});

0 commit comments

Comments
 (0)