Categories
interview

Binary search

const binarySearch = (arr, x) => {
  let low = 0;
  let high = arr.length - 1;
  while (low <= high) {
    const mid = low + Math.floor((high - low) /
 2);
    if (x === arr[mid]) {
      return mid;
    } else if (x < arr[mid]) {
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }
  return -1;
};

const inpArr = [-1, 0, 2, 4, 9, 10, 3000];

console.log(binarySearch(inpArr, 2));  // 2

console.log(binarySearch(inpArr, 11)); // -1

// Runtime Complexity O(log(n))
// Space Complexity O(1)

Demo