Created
August 12, 2024 06:47
-
-
Save kshirish/a9996869cebdc13c304a998e14c78657 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(arr, value) { | |
let leftIndex = 0; | |
let rightIndex = arr.length - 1; | |
while(leftIndex <= rightIndex) { | |
let middleIndex = Math.floor((leftIndex + rightIndex)/2); | |
if(arr[middleIndex] === value) { | |
return middleIndex; | |
} else if(arr[middleIndex] < value) { | |
leftIndex = middleIndex + 1; | |
} else { | |
rightIndex = middleIndex - 1; | |
} | |
} | |
return -1; | |
} | |
console.log(binarySearch([2, 8, 10, 14, 33, 61, 117], 117)); | |
console.log(binarySearch([1, 3, 9, 12, 110], 1)); | |
console.log(binarySearch([-5, 1, 4, 332], 4)); | |
console.log(binarySearch([-5, 1, 4, 332], 14)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment