Created
July 11, 2022 01:56
-
-
Save CarlaTeo/5a13bd807889e5fce092aad35237a0ef 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
function binarySearch(array, value) { | |
let i = 0; | |
let j = array.length - 1; | |
while(i <= j) { | |
const middle = Math.floor((j + i) / 2); | |
if(array[middle] === value) return middle; | |
if(array[middle] > value) j = middle - 1; | |
else i = middle + 1; | |
} | |
return -1; | |
} | |
console.log(binarySearch([3,5,7,10,18], 10)); // 3 | |
console.log(binarySearch([3,5,7,10,18], 0)); // -1 | |
console.log(binarySearch([3,5,7,10,18], 5)); // 2 | |
console.log(binarySearch([], 10)); // -1 | |
console.log(binarySearch([10], 10)); // 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment