Last active
July 23, 2019 03:36
-
-
Save motss/ba70731dc3f4410d993d732d6893fcdf to your computer and use it in GitHub Desktop.
Binary Search (recursive or iterative implementations)
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 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); |
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 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