Skip to content

Commit afb11e4

Browse files
authored
Create WiggleSort.js
Added Wiggle Sort Algorithm
1 parent 86d333e commit afb11e4

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Sorts/WiggleSort.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Wiggle Sort is a sorting algorithm that arranges the elements of an array
2+
// in a "wiggle" pattern, where each element is alternately smaller and larger
3+
// than its adjacent elements.
4+
5+
// Function to perform Wiggle Sort on an array
6+
function wiggleSort(nums) {
7+
const n = nums.length;
8+
9+
// Step 1: Sort the input array in ascending order
10+
nums.sort((a, b) => a - b);
11+
12+
// Step 2: Create a new array to store the result
13+
const result = new Array(n);
14+
15+
// Initialize pointers and index variables
16+
let left = 0;
17+
let right = n - 1;
18+
let mid = Math.floor((n - 1) / 2);
19+
let i = 0;
20+
21+
// Step 3: Fill the result array with the wiggle-sorted values
22+
while (i < n) {
23+
// Alternate between placing the larger values (right) and smaller values (mid) into the result array
24+
if (i % 2 === 0) {
25+
result[i] = nums[mid];
26+
mid--;
27+
} else {
28+
result[i] = nums[right];
29+
right--;
30+
}
31+
i++;
32+
}
33+
34+
// Step 4: Copy the result back to the original array
35+
for (let j = 0; j < n; j++) {
36+
nums[j] = result[j];
37+
}
38+
}
39+
40+
// Example usage
41+
const nums = [3, 5, 2, 1, 6, 4];
42+
console.log("Original Array:", nums);
43+
44+
// Perform Wiggle Sort on the array
45+
wiggleSort(nums);
46+
47+
console.log("Wiggle-Sorted Array:", nums);

0 commit comments

Comments
 (0)