Created
July 5, 2023 11:21
-
-
Save AshishKapoor/d8e2073d26d9355297e54c0690b87114 to your computer and use it in GitHub Desktop.
Binary search to find the target value in a sorted array.
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(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