Skip to content

Commit 60889e3

Browse files
committed
Sleep Sort
Added Sleep Sort Algorithm
1 parent 33bd28b commit 60889e3

File tree

4 files changed

+801
-21
lines changed

4 files changed

+801
-21
lines changed

Sorts/SleepSort.js

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,10 @@ async function sleepSort(arr) {
3131
throw new Error('Input must be an array.');
3232
}
3333

34-
const sortedArray = [];
35-
const promises = [];
34+
const promises = arr.map(num => sleep(num).then(() => num));
35+
const sortedArray = await Promise.all(promises);
3636

37-
for (const num of arr) {
38-
promises.push(new Promise(resolve => {
39-
setTimeout(async () => {
40-
sortedArray.push(num);
41-
resolve();
42-
}, num);
43-
}));
44-
}
45-
46-
await Promise.all(promises);
4737
return sortedArray.sort((a, b) => a - b);
4838
}
4939

5040
export default sleepSort;
51-
52-

Sorts/test/SleepSort.test.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
1-
/**
2-
* Jest tests for the sleepSort function.
3-
*/
4-
import sleepSort from '../SleepSort'; // Update the import path as needed
1+
import { expect } from 'chai';
2+
import sleepSort from '../SleepSort';
53

64
describe('sleepSort', () => {
75
it('should return an empty array when given an empty array', async () => {
86
const result = await sleepSort([]);
9-
expect(result).toEqual([]);
7+
expect(result).to.deep.equal([]);
108
});
119

1210
it('should sort the input array using sleep sort', async () => {
1311
const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
1412
const result = await sleepSort(input);
1513
const sortedInput = input.slice().sort((a, b) => a - b);
16-
expect(result).toEqual(sortedInput);
14+
expect(result).to.deep.equal(sortedInput);
1715
});
1816

1917
it('should handle duplicate values correctly', async () => {
2018
const input = [3, 2, 1, 9, 8, 4, 2];
2119
const result = await sleepSort(input);
2220
const sortedInput = input.slice().sort((a, b) => a - b);
23-
expect(result).toEqual(sortedInput);
21+
expect(result).to.deep.equal(sortedInput);
2422
});
2523
});
2624

25+
26+

0 commit comments

Comments
 (0)