Skip to content

Commit 53355cc

Browse files
committed
feat: implement sleep sort
Signed-off-by: David Edler <david.edler@canonical.com>
1 parent 08d8c6b commit 53355cc

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

Sorts/SleepSort.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Implementation of the sleep sort algorithm.
3+
*
4+
* This sorting algorithm delays each input element by an amount of time
5+
* proportional to its value before adding it to the result
6+
*
7+
* @see https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
8+
*/
9+
export function sleepSort(arr) {
10+
return new Promise((resolve) => {
11+
const result = []
12+
let count = 0
13+
14+
arr.forEach((num) => {
15+
// Use setTimeout proportional to the number
16+
setTimeout(() => {
17+
result.push(num)
18+
count++
19+
if (count === arr.length) {
20+
resolve(result)
21+
}
22+
}, num)
23+
})
24+
})
25+
}

Sorts/test/SleepSort.test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { sleepSort } from '../SleepSort.js'
2+
3+
describe('sleepSort', () => {
4+
it('should sort the array', async () => {
5+
const result = await sleepSort([5, 6, 7, 8, 1, 2, 12, 14])
6+
expect(result).toEqual([1, 2, 5, 6, 7, 8, 12, 14])
7+
})
8+
})

0 commit comments

Comments
 (0)