DSA Basics: Binary Search

Learn binary search on sorted arrays with the left, right, and mid pointer pattern.

Back to Learn DSA

Binary search is an efficient search algorithm for sorted arrays. Instead of checking every value, it repeatedly cuts the search area in half.

The important condition is that the input must be sorted. If the values are not sorted, binary search cannot safely decide which half to discard.

Core idea

Keep two pointers:

If values[mid] is too small, move left to mid + 1. If it is too large, move right to mid - 1.

function binarySearch(values, target) {
	let left = 0;
	let right = values.length - 1;

	while (left <= right) {
		const mid = Math.floor((left + right) / 2);

		if (values[mid] === target) return mid;
		if (values[mid] < target) left = mid + 1;
		else right = mid - 1;
	}

	return -1;
}

Why it is fast

Every step removes half of the remaining search space. For 1,000,000 sorted values, binary search needs about 20 checks, not one million.

Complexity

Common mistakes

Practice problems

  1. Search a sorted array.
  2. Find the first occurrence of a value.
  3. Find the last occurrence of a value.
  4. Find the insert position for a target.
  5. Find the smallest value greater than or equal to a target.

Interactive walkthrough

Binary Search Visualizer

Watch left, mid, and right narrow the search range.
Step 1 L=0
Step 2 mid=3
Step 3 R=7
Step 4 target=31