Binary Search

An efficient algorithm for finding a target value in a sorted array by repeatedly dividing the search interval in half.

Binary Search Visualization

Search Engine

Binary Search Visualizer

O(log n)
range: [, ]
SlowFast
Target

Steps

0

Runtime Feed

Live Execution

Ready
Status

Generate an array and enter a target value to search.

Synced Logic

1let low = 0;
2let high = arr.length - 1;
3while (low <= high) {
4 const mid = Math.floor((low + high) / 2);
5 if (arr[mid] === target) return mid;
6 else if (arr[mid] < target) low = mid + 1;
7 else high = mid - 1;
8}
9return -1;
MidActive rangeFoundEliminated↓ low↑ mid↓ high

Search Timeline

Step History

0 / 0

Timeline is waiting for execution...

Run the search or use Step mode to populate this panel.

Complexity

Time Complexity: O(log n)
Space Complexity: O(1)

Pseudocode

function binarySearch(arr, target):
  left = 0
  right = length(arr) - 1
  while left <= right:
    mid = floor((left + right) / 2)
    if arr[mid] == target:
      return mid
    else if arr[mid] < target:
      left = mid + 1
    else:
      right = mid - 1
  return -1