Created
July 7, 2020 19:20
-
-
Save piontekle/0d57c6cd4e6dafb2d2c34a1e72990261 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Searching | |
const sortedLgArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]; | |
// Linear - O(n) | |
function linearSearch(arr, val) { | |
for (let i = 0; i < arr.length; i++) { | |
if (arr[i] === val) return arr[i]; | |
} | |
return "Not found."; | |
} | |
Binary - O(log(n)) | |
function binarySearch(arr, val) { | |
if (arr.length <= 1) return arr[0] === val ? arr[0] : "Not found."; | |
let mid = Math.floor(arr.length/2); | |
if (arr[mid] === val) return arr[mid] | |
else if (val < arr[mid]) return binarySearch(arr.slice(0, mid), val) | |
else return binarySearch(arr.slice(mid), val) | |
} | |
const tester = { | |
1: { test: "should return expected non-edge val: ", val: 5, ans: 5 }, | |
2: { test: "should return expected edge val: ", val: 39, ans: 39 }, | |
3: { test: "should return not found: ", val: 55, ans: "Not found." } | |
} | |
Object.keys(tester).forEach(key => { | |
// console.log("--------------------------"); | |
// console.log(tester[key]["test"]); | |
// console.log(linearSearch(sortedLgArr, tester[key]["val"]) === tester[key]["ans"]); | |
console.log("--------------------------"); | |
console.log(tester[key]["test"]); | |
console.log(binarySearch(sortedLgArr, tester[key]["val"]) === tester[key]["ans"]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment