Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Sorts/SleepSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Implementation of the sleep sort algorithm.
*
* This sorting algorithm delays each input element by an amount of time
* proportional to its value before adding it to the result
*
* @see https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
*/
export function sleepSort(arr) {
return new Promise((resolve) => {
const result = []
let count = 0

arr.forEach((num) => {
// Use setTimeout proportional to the number
setTimeout(() => {
result.push(num)
count++
if (count === arr.length) {
resolve(result)
}
}, num)
})
})
}
8 changes: 8 additions & 0 deletions Sorts/test/SleepSort.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { sleepSort } from '../SleepSort.js'

describe('sleepSort', () => {
it('should sort the array', async () => {
const result = await sleepSort([5, 6, 7, 8, 1, 2, 12, 14])
expect(result).toEqual([1, 2, 5, 6, 7, 8, 12, 14])
})
})