From 4b47c0661b4b7a75c498b008d03324247de22d0a Mon Sep 17 00:00:00 2001 From: Akarsh Date: Thu, 25 Apr 2019 21:58:03 +0530 Subject: [PATCH] Add wiggle sort --- Sorts/wiggleSort.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Sorts/wiggleSort.js diff --git a/Sorts/wiggleSort.js b/Sorts/wiggleSort.js new file mode 100644 index 000000000..6424a1a1b --- /dev/null +++ b/Sorts/wiggleSort.js @@ -0,0 +1,26 @@ +/* +* 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 ]