Skip to content

Commit 4de0e55

Browse files
authored
Create WiggleSort.js
Added Wiggle Sort
1 parent 1de5ab7 commit 4de0e55

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Sorts/WiggleSort.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
54+
/**
55+
* Jest tests for the wiggleSort function.
56+
*/
57+
describe("wiggleSort", () => {
58+
it("should return an empty array when given an empty array", () => {
59+
expect(wiggleSort([])).toEqual([]);
60+
});
61+
62+
it("should sort the input array in a wiggle pattern", () => {
63+
expect(wiggleSort([3, 5, 2, 1, 6, 4])).toEqual([1, 6, 2, 5, 3, 4]);
64+
expect(wiggleSort([5, 3, 1, 2, 6, 4])).toEqual([1, 6, 2, 5, 3, 4]);
65+
});
66+
67+
it("should handle duplicate values correctly", () => {
68+
expect(wiggleSort([3, 3, 3, 3, 3])).toEqual([3, 3, 3, 3, 3]);
69+
expect(wiggleSort([3, 3, 3, 2, 2, 1])).toEqual([2, 3, 2, 3, 1, 3]);
70+
});
71+
});

0 commit comments

Comments
 (0)