Skip to content

Instantly share code, notes, and snippets.

@hellokvn
Last active February 11, 2024 11:12
Show Gist options
  • Save hellokvn/9df8ee1457a89a672e9d723746199e46 to your computer and use it in GitHub Desktop.
Save hellokvn/9df8ee1457a89a672e9d723746199e46 to your computer and use it in GitHub Desktop.
Binary Search
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