Created
February 10, 2020 03:57
-
-
Save StevenXL/188dfbb08aca4be8dc2566f5051b7d2d to your computer and use it in GitHub Desktop.
Modified Binary Search
This file contains 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(arr, k, searchType) { | |
let left = 0; | |
let right = arr.length - 1; | |
let ans = null; | |
while (left <= right) { | |
const midIdx = Math.floor((left + right) / 2); | |
const el = arr[midIdx]; | |
if (el === k) { | |
ans = midIdx; | |
if (searchType === SEARCH_TYPE.FIRST) { | |
right = midIdx - 1; | |
} else { | |
left = midIdx + 1; | |
} | |
} else if (el > k) { | |
right = midIdx - 1; | |
} else if (el < k) { | |
left = midIdx + 1; | |
} | |
} | |
return ans; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment