Skip to content

Instantly share code, notes, and snippets.

@AshishKapoor
Created July 5, 2023 11:21
Show Gist options
  • Save AshishKapoor/d8e2073d26d9355297e54c0690b87114 to your computer and use it in GitHub Desktop.
Save AshishKapoor/d8e2073d26d9355297e54c0690b87114 to your computer and use it in GitHub Desktop.
Binary search to find the target value in a sorted array.
function binarySearch(nums, target) {
let left = 0;
let right = nums.length - 1
while (left <= right) {
let mid = ~~((left + right)/2)
if (nums[mid] === target) return mid
if (nums[mid] < target) left = mid + 1
if (target < nums[mid]) right = mid - 1
}
return -1
}
console.log(binarySearch([0,2,3,4,5,6,7,8], 6)) // Output: 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment