Skip to content

Instantly share code, notes, and snippets.

@mnikn
Last active June 19, 2019 07:09
Show Gist options
  • Save mnikn/df130375a0f41894f651268c8b32ba1e to your computer and use it in GitHub Desktop.
Save mnikn/df130375a0f41894f651268c8b32ba1e to your computer and use it in GitHub Desktop.
[search] search algorithm #algorithm
function binarySearch(nums, target) {
let i = 0, j = nums.length - 1;
while (i <= j) {
const mid = (i + j) >> 1;
if (nums[mid] === target) return mid;
else if (nums[mid] > target) j = mid;
else i = mid + 1;
}
return -1;
}
function binarySearchLeft(nums, target) {
let i = 0, j = nums.length - 1;
while (i < j) {
const mid = (i + j) >> 1;
if (nums[mid] < target) i = mid + 1;
else j = mid;
}
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment