Created
February 15, 2021 13:39
-
-
Save MohammedALREAI/a1bcfea069543a0d306dcac1abcc146c to your computer and use it in GitHub Desktop.
Binary Search leetcode
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 search(nums: number[], target: number): number { | |
let left=0; | |
let right=nums.length-1 | |
while (left <= right) { | |
const middle = Math.floor((left + right) / 2); | |
const potentialMatch = nums[middle]; | |
if (target === potentialMatch) { | |
return middle; | |
} else if (target < potentialMatch) { | |
right = middle - 1; | |
} else { | |
left = middle + 1; | |
} | |
} | |
return -1;} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment