Binary search

Easy TimeO(log n) SpaceO(1)

Given an array arr sorted in ascending order and a target, return the index where the target sits, or -1 when it is not there. If the target appears more than once, any of its indices will do, and an empty array holds nothing so the answer is -1.

Examples

Example 1

Input
arr = [1, 3, 5, 7, 9, 11, 13]target = 9
Output
4
Counting from 0, the 9 in [1, 3, 5, 7, 9, 11, 13] sits at index 4.

Example 2

Input
arr = [1, 3, 5, 7, 9, 11, 13]target = 4
Output
-1
The array holds only odd values, so 4 is absent.

The Code

function binarySearch(arr, target) {
  let lo = 0;
  let hi = arr.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}
binarySearch([1, 3, 5, 7, 9, 11, 13], 9);
Done
Step through binarySearch([1, 3, 5, 7, 9, 11, 13], 9) call by call