-
-
Save abenteuerzeit/9e8ce085ce10ec25c8568eb0e97195d2 to your computer and use it in GitHub Desktop.
Binary Search
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
const binarySearch = (arr, target) => { | |
let left = 0; | |
let right = arr.length; | |
while (right > left) { | |
const indexToCheck = Math.floor((left + right) / 2); | |
const checking = arr[indexToCheck]; | |
console.log(indexToCheck); | |
if (checking === target) { | |
return indexToCheck; | |
} else if (checking < target) { | |
left = indexToCheck + 1; | |
} else { | |
right = indexToCheck; | |
} | |
} | |
return null; | |
} | |
const searchable = [1, 2, 7, 8, 22, 28, 41, 58, 67, 71, 94]; | |
const target = 41; | |
targetIndex = binarySearch(searchable, target); | |
console.log(`The target index is ${targetIndex}.`); | |
module.exports = binarySearch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment