Files
JavaScript/Sorts/wiggleSort.js
PatOnTheBack f37cac8508 Fixed Whitespace, Operators, and Quotes to Comply with JSLint
I modified the whitespace in the files and changed single quotes to double quotes.

I also changed some `==` and `!=` operators to `===` and `!==` to comply with JSLint.
2019-06-27 10:41:44 -04:00

27 lines
720 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* Wiggle sort sorts the array into a wave like array.
* An array arr[0..n-1] is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= …..
*
*/
Array.prototype.wiggleSort = function () {
for (let i = 0; i < this.length; ++i) {
const shouldNotBeLessThan = i % 2;
const isLessThan = this[i] < this[i + 1];
if (shouldNotBeLessThan && isLessThan) {
[this[i], this[i + 1]] = [this[i + 1], this[i]];
}
}
return this;
};
//Implementation of wiggle sort
var arr = [3, 5, 2, 1, 6, 4];
//Array before Wiggle Sort
console.log(arr); //[3, 5, 2, 1, 6, 4]
arr.wiggleSort()
//Array after wiggle sort
console.log(arr); // [ 3, 5, 2, 6, 1, 4 ]