Binary Search

Binary Search is an efficient search algorithm that works on sorted arrays by repeatedly dividing the search interval in half.

If the target value is less than the middle element, the search continues in the left half; otherwise, in the right half. This reduces the time complexity to O(log n).

Example

// Binary Search in JavaScript
function binarySearch(arr, target) {
  let left = 0, right = arr.length - 1;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}

const result = binarySearch([1, 3, 5, 7, 9], 5);
console.log(result); // Output: 2
Binary Search

Build Array

6 elements

Binary search needs sorted data. New slots start as NULL — fill them in ascending order using Push or Insert below.

Search

Repeatedly halves the range using the midpoint.

Iterations: 0
Speed
Array Visualizer
6 elements
Low
High
22
25
32
48
51
73
Low / High
Mid (checking)
Eliminated range
Found
Real-life Use (Binary Search)

Binary search is used when you have a large, sorted dataset and want to find an item quickly without scanning every element.

A common example is looking up a word in a dictionary — you don’t start from the first page; you open around the middle and adjust based on alphabetical order.

Example

// Simulating binary search use in dictionary
const words = ["Apple", "Banana", "Grape", "Mango", "Peach"];
console.log(binarySearch(words, "Mango")); // Output: 3