Skip to content

Visualizers

Binary Search Visualizer

Step-through animation of Binary Search on a sorted array.

native (Canvas API) Client-side
Ready to visualize

Execution Log

Comparisons: 0
Low Pointer (L): 0
Mid Pointer (M): -
High Pointer (H): -
Current Action:

Idle

Legend:

Out of Search Range
In Search Range
Boundary (L / H)
Midpoint check
Match Found

Binary Search Algorithm

Binary Search is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are not equal, the half in which the target cannot lie is eliminated, and the search continues on the remaining half.

How It Works

  1. Start with the search range covering the entire sorted array: low = 0, high = N - 1.
  2. Compute mid = floor((low + high) / 2).
  3. If array[mid] matches target, return mid.
  4. If array[mid] is less than target, search the right half: low = mid + 1.
  5. If array[mid] is greater than target, search the left half: high = mid - 1.
  6. Repeat until low > high (element not found).

Implementation

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; // index found
    } else if (arr[mid] < target) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return -1; // not found
}