Created
February 20, 2024 00:45
-
-
Save tdubs42/5f9233f98393f9b7cbbe9eebc025cd15 to your computer and use it in GitHub Desktop.
Binary Search Function for Sorted List - 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
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; | |
} | |
module.exports = binarySearch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment