1
+ /**
2
+ * Sleep Sort is a sorting algorithm that sorts an array of non-negative integers.
3
+ * It works by "sleeping" for a duration proportional to each element's value.
4
+ * Elements with smaller values will "wake up" earlier and appear earlier in the sorted result.
5
+ *
6
+ * @param {number[] } arr - The array of non-negative integers to be sorted.
7
+ * @returns {Promise<number[]> } - A Promise that resolves to the sorted array.
8
+ *
9
+ * @example
10
+ * const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
11
+ * sleepSort(input).then((result) => {
12
+ * console.log(result); // Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
13
+ * });
14
+ *
15
+ * Time Complexity: O(k * n)
16
+ * - k is the maximum value in the input array.
17
+ * - Sleeping for each element takes O(k) time, and there are n elements in the array.
18
+ * - Therefore, the time complexity is O(k * n).
19
+ *
20
+ * Space Complexity: O(n)
21
+ * - Additional space is required for the result array, which has n elements.
22
+ * - The space complexity is O(n).
23
+ */
24
+ export function sleepSort ( arr ) {
25
+ // Helper function to sleep for a given duration (in milliseconds)
26
+ function sleep ( duration ) {
27
+ return new Promise ( ( resolve ) => setTimeout ( resolve , duration ) ) ;
28
+ }
29
+
30
+ // Function to perform the sleep sort
31
+ async function performSleepSort ( ) {
32
+ const result = [ ] ;
33
+ for ( const num of arr ) {
34
+ // Sleep for a duration proportional to the element's value
35
+ await sleep ( num ) ;
36
+ result . push ( num ) ;
37
+ }
38
+ return result ;
39
+ }
40
+
41
+ return performSleepSort ( ) ;
42
+ }
43
+
44
+
0 commit comments