Last active
February 11, 2024 11:12
-
-
Save hellokvn/9df8ee1457a89a672e9d723746199e46 to your computer and use it in GitHub Desktop.
Binary Search
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(nums: number[], target: number): number { | |
let left: number = 0; | |
let right: number = nums.length - 1; | |
while (left <= right) { | |
const mid: number = Math.floor((left + right) / 2); | |
if (nums[mid] === target) return mid; | |
if (target < nums[mid]) right = mid - 1; | |
else left = mid + 1; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment