Frontend Knowledge Base
Searching

Binary Search

  1. Initialize left and right pointers to the start and end of the array
  2. While left is less than or equal to right
    1. Calculate the middle index
    2. If the middle element is the target, return the index
    3. If the middle element is less than the target, move the left pointer to the middle + 1
    4. If the middle element is greater than the target, move the right pointer to the middle - 1
  3. If the target is not found, return -1
function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) {
      return mid;
    } else if (arr[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1;
}

Key Points

  • The array must be sorted for binary search to work
  • The time complexity is O(log n)
  • The space complexity is O(1)

Variants

Binary Search with Recursion

function binarySearchRecursive(arr, target, left, right) {
  if (left > right) {
    return -1;
  }

  const mid = Math.floor((left + right) / 2);
  if (arr[mid] === target) {
    return mid;
  } else if (arr[mid] < target) {
    return binarySearchRecursive(arr, target, mid + 1, right);
  } else {
    return binarySearchRecursive(arr, target, left, mid - 1);
  }
}

Binary Search with same elements

function binarySearchSameElements(arr, target) {
  let left = 0;
  let right = arr.length - 1;
  let result = -1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) {
      result = mid;
      right = mid - 1;
    } else if (arr[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return result;
}

Explanation: For the same elements, we need to find the first occurrence of the target. So we need to move the right pointer to the middle - 1 when the middle element is equal to the target. This way, we will find the first occurrence of the target.