Add ES6 Examples to all chapters (#38)

* add ES6 example for binary search

* add ES6 example for selection sort

* add ES6 example for countdown

* add ES6 example for greet

* add ES6 example for factorial

* edit ES6 example for quicksort

* add ES6 example for loop sum

* add ES6 example for recursive sum

* add ES6 example for recursive count

* add ES6 example for recursive max

* add ES6 example for price of groceries

* add ES6 example for check voter

* add ES6 example for breadth-first search

* add ES6 example for dijkstras algorithm

* edit ES6 example for dijkstras algorithm

* edit ES6 example for set covering

* add ES6 example for longest common subsequence
This commit is contained in:
Yossi Adler
2017-11-13 18:12:59 +02:00
committed by Aditya Bhargava
parent 1a81d3e6b2
commit ec2890a93d
20 changed files with 328 additions and 18 deletions

View File

@@ -0,0 +1,26 @@
// Finds the smallest value in an array
const findSmallest = (arr) => {
let smallest = arr[0]; // Stores the smallest value
let smallestIndex = 0; // Stores the index of the smallest value
for (let i = 1; i < arr.length; i += 1) {
if (arr[i] < smallest) {
smallest = arr[i];
smallestIndex = i;
}
}
return smallestIndex;
};
// Sort array
const selectionSort = (arr) => {
const newArr = [];
const length = arr.length;
for (let i = 0; i < length; i += 1) {
// Finds the smallest element in the array and adds it to the new array
const smallest = findSmallest(arr);
newArr.push(arr.splice(smallest, 1)[0]);
}
return newArr;
};
console.log(selectionSort([5, 3, 6, 2, 10])); // [2, 3, 5, 6, 10]