1
+ /**
2
+ * Wiggle Sort is a sorting algorithm that arranges elements of an array in a "wiggle" pattern.
3
+ * Even-indexed elements are smaller or equal to their adjacent elements, and odd-indexed elements
4
+ * are larger or equal to their adjacent elements.
5
+ *
6
+ * @param {number[] } arr - The array to be sorted in a wiggle pattern.
7
+ * @returns {number[] } - The array sorted in a wiggle pattern.
8
+ *
9
+ * @example
10
+ * const input = [3, 5, 2, 1, 6, 4];
11
+ * const result = wiggleSort(input);
12
+ * console.log(result); // Output: [1, 6, 2, 5, 3, 4]
13
+ *
14
+ * Time Complexity: O(n log n)
15
+ * - Sorting the array takes O(n log n) time using JavaScript's built-in sort method.
16
+ * - Filling the result array takes O(n) time.
17
+ *
18
+ * Overall, the time complexity is dominated by the sorting step.
19
+ *
20
+ * Space Complexity: O(n)
21
+ * - Additional space is required for the cloned array and the result array.
22
+ * - The space complexity is O(n).
23
+ */
24
+ export function wiggleSort ( arr ) {
25
+ // Clone the input array to avoid modifying the original array
26
+ const clonedArr = [ ...arr ] ;
27
+
28
+ // Sort the cloned array in ascending order
29
+ clonedArr . sort ( ( a , b ) => a - b ) ;
30
+
31
+ // Create a new array to store the result
32
+ const result = new Array ( clonedArr . length ) ;
33
+
34
+ // Initialize pointers
35
+ let left = 0 ;
36
+ let right = clonedArr . length - 1 ;
37
+
38
+ // Fill the result array with the wiggle-sorted values
39
+ for ( let i = 0 ; i < result . length ; i ++ ) {
40
+ if ( i % 2 === 0 ) {
41
+ // Place smaller or equal values at even indices
42
+ result [ i ] = clonedArr [ left ] ;
43
+ left ++ ;
44
+ } else {
45
+ // Place larger or equal values at odd indices
46
+ result [ i ] = clonedArr [ right ] ;
47
+ right -- ;
48
+ }
49
+ }
50
+
51
+ return result ;
52
+ }
53
+
0 commit comments