Created
July 22, 2019 17:29
-
-
Save Gosilama/bdd5d47512859030609b757f3b857dc6 to your computer and use it in GitHub Desktop.
A very simplistic implementation of the binary search algorithm in javascript
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
// Simple Binary search implementation in Js | |
const binarySearch = (arr, key) => { | |
if (arr == null || typeof arr === 'undefined') return null; | |
if (arr.length === 1) { | |
if (key === arr[0]) { | |
return arr[0]; | |
} else { | |
return 'not found'; | |
} | |
} | |
let i = Math.floor(arr.length / 2); | |
for (let j = 0 ; j < i; j++) { | |
if (key === arr[j]) { | |
return arr[j]; | |
} | |
} | |
let newArrToSearch = arr.slice(i); | |
return binarySearch(newArrToSearch, key); | |
} | |
const testBinarySearch = (arrayToSearch, key) => { | |
const result = binarySearch(arrayToSearch, key); | |
console.log(result); | |
} | |
testBinarySearch([1,2,310, 5, 23, 9], 1); | |
testBinarySearch(['dog', 'cat', 'some random text'], 'cat'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment