Explore Library
Code QuizAdvanced

Binary Search Boundary Bug

Spot the subtle boundary mistake that breaks this binary search implementation.

Codejavascript
function binarySearch(arr, target) {
  let low = 0;
  let high = arr.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);

    if (arr[mid] === target) {
      return mid;
    } else if (arr[mid] < target) {
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }

  return -1;
}

This binary search often fails to find existing elements. What is the bug?