diff --git a/Sorts/SleepSort.js b/Sorts/SleepSort.js new file mode 100644 index 0000000000..bec11792fd --- /dev/null +++ b/Sorts/SleepSort.js @@ -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) + }) + }) +} diff --git a/Sorts/test/SleepSort.test.js b/Sorts/test/SleepSort.test.js new file mode 100644 index 0000000000..21c8b79614 --- /dev/null +++ b/Sorts/test/SleepSort.test.js @@ -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]) + }) +})