Last active
June 19, 2019 07:09
-
-
Save mnikn/df130375a0f41894f651268c8b32ba1e to your computer and use it in GitHub Desktop.
[search] search algorithm #algorithm
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, 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