Skip to content

Instantly share code, notes, and snippets.

@Gosilama
Created July 22, 2019 17:29
Show Gist options
  • Save Gosilama/bdd5d47512859030609b757f3b857dc6 to your computer and use it in GitHub Desktop.
Save Gosilama/bdd5d47512859030609b757f3b857dc6 to your computer and use it in GitHub Desktop.
A very simplistic implementation of the binary search algorithm in javascript
// 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