Skip to content

Instantly share code, notes, and snippets.

@motss
Last active July 23, 2019 03:36
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 motss/ba70731dc3f4410d993d732d6893fcdf to your computer and use it in GitHub Desktop.
Save motss/ba70731dc3f4410d993d732d6893fcdf to your computer and use it in GitHub Desktop.
Binary Search (recursive or iterative implementations)
function bsr(arr, m) {
let l = 0;
let r = arr.length - 1;
while (l <= r) {
const mid = (l + (r - l) / 2) | 0;
const val = arr[mid];
if (val === m) return mid;
if (m > val) l = mid + 1;
if (m < val) r = mid - 1;
}
return -1;
}
a = [1, 2, 3, 4, 5, 6, 7, 8, 10, 12];
b = 3;
bsr(a, b);
function bsr(arr, l, r, m) {
const mid = (l + (r - l) / 2) | 0;
const val = arr[mid];
// Ensure `l` is always less than or equal to `r`.
// When `m` is not inside `arr`, `l` will exceed `r`
// which is the the last index of `arr` as we are
// always adding 1 to `l` when `m > val` fulfills.
if (l <= r) {
if (val === m) return mid;
if (m > val) return bs(arr, mid + 1, r, m);
if (m < val) return bs(arr, l, mid - 1, m);
}
return -1;
}
a = [1, 2, 3, 4, 5, 6, 7, 8, 10, 12];
b = 3;
c = bsr(a, 0, a.length - 1, b);
c;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment