Skip to content

Instantly share code, notes, and snippets.

@StevenXL
Created February 10, 2020 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenXL/188dfbb08aca4be8dc2566f5051b7d2d to your computer and use it in GitHub Desktop.
Save StevenXL/188dfbb08aca4be8dc2566f5051b7d2d to your computer and use it in GitHub Desktop.
Modified Binary Search
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