Skip to content

Instantly share code, notes, and snippets.

@kshirish
Created August 12, 2024 06:47
Show Gist options
  • Save kshirish/a9996869cebdc13c304a998e14c78657 to your computer and use it in GitHub Desktop.
Save kshirish/a9996869cebdc13c304a998e14c78657 to your computer and use it in GitHub Desktop.
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