Skip to content

Commit 4b47c06

Browse files
committed
Add wiggle sort
1 parent ad001c4 commit 4b47c06

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Sorts/wiggleSort.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* Wiggle sort sorts the array into a wave like array.
3+
* An array ‘arr[0..n-1]’ is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= …..
4+
*
5+
*/
6+
7+
Array.prototype.wiggleSort = function() {
8+
for (let i = 0; i < this.length; ++i) {
9+
const shouldNotBeLessThan = i % 2;
10+
const isLessThan = this[i] < this[i + 1];
11+
if (shouldNotBeLessThan && isLessThan) {
12+
[this[i], this[i + 1]] = [this[i + 1], this[i]];
13+
}
14+
}
15+
return this;
16+
};
17+
18+
//Implementation of wiggle sort
19+
20+
var arr = [3, 5, 2, 1, 6, 4];
21+
//Array before Wiggle Sort
22+
console.log(arr); //[3, 5, 2, 1, 6, 4]
23+
24+
arr.wiggleSort()
25+
//Array after wiggle sort
26+
console.log(arr); // [ 3, 5, 2, 6, 1, 4 ]

0 commit comments

Comments
 (0)