Blog
2026-06-30T00:00:00.000Z binary searchsearchbeginner dsa

Binary Search Works Because of Order

Learn the one condition that makes binary search possible and why sorted data changes the cost of searching.

The One Requirement

Binary search needs sorted data, or at least a search space where answers move in one direction.

Without order, the middle value tells you almost nothing. With order, the middle value tells you which half can be ignored.

The Mental Model

Imagine guessing a number between 1 and 100. If the answer is higher than 50, every number from 1 to 50 is gone from consideration.

That is the whole trick: each comparison removes about half of the remaining possibilities.

TypeScript
function binarySearch(values: number[], target: number) {
  let low = 0;
  let high = values.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);

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

  return -1;
}
Python
def binary_search(values, target):
    low = 0
    high = len(values) - 1

    while low <= high:
        mid = (low + high) // 2

        if values[mid] == target:
            return mid
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1

    return -1

Common Beginner Mistake

Do not use binary search on unsorted data. Sorting first can be useful, but sorting costs time too, so count that cost in the full solution.