Merge pull request #88 from PatOnTheBack/master

Improved JSLint Compliance and Created Math Algorithms
This commit is contained in:
Yang Libin
2019-08-07 18:33:05 +08:00
committed by GitHub
12 changed files with 289 additions and 143 deletions

View File

@@ -1,48 +1,48 @@
/*
* A simple helper function that checks, if the array is
* sorted in ascending order.
*/
Array.prototype.isSorted = function() {
* A simple helper function that checks, if the array is
* sorted in ascending order.
*/
Array.prototype.isSorted = function () {
let length = this.length;
let length = this.length;
if (length < 2) {
return true;
}
for (let i = 0; i < length - 1; i++) {
if (this[i] > this[i + 1]) {
return false;
if (length < 2) {
return true;
}
}
return true;
for (let i = 0; i < length - 1; i++) {
if (this[i] > this[i + 1]) {
return false;
}
}
return true;
};
/*
* A simple helper function to shuffle the array randomly in place.
*/
Array.prototype.shuffle = function() {
* A simple helper function to shuffle the array randomly in place.
*/
Array.prototype.shuffle = function () {
for (let i = this.length -1; i; i--) {
let m = Math.floor(Math.random() * i);
let n = this[i - 1];
this[i - 1] = this[m];
this[m] = n;
}
for (let i = this.length - 1; i; i--) {
let m = Math.floor(Math.random() * i);
let n = this[i - 1];
this[i - 1] = this[m];
this[m] = n;
}
};
/*
* Implementation of the bogosort algorithm. This sorting algorithm randomly
* rearranges the array until it is sorted.
* For more information see: https://en.wikipedia.org/wiki/Bogosort
*/
* Implementation of the bogosort algorithm. This sorting algorithm randomly
* rearranges the array until it is sorted.
* For more information see: https://en.wikipedia.org/wiki/Bogosort
*/
function bogoSort(items) {
while(!items.isSorted()){
items.shuffle()
}
return items;
while (!items.isSorted()) {
items.shuffle()
}
return items;
}
//Implementation of bogoSort
@@ -52,4 +52,4 @@ var ar = [5, 6, 7, 8, 1, 2, 12, 14];
console.log(ar);
bogoSort(ar);
//Array after sort
console.log(ar);
console.log(ar);

View File

@@ -1,18 +1,18 @@
/*
* 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] >= …..
*
*/
* 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]];
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;
return this;
};
//Implementation of wiggle sort