Skip to article content
FrontendXLesson 05 / 24

Binary search and halving

Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.

beginner · about 30 minutes · 3 exercises

  • Predict
  • Explain
  • Debug

What you will be able to do

#
  • Implement binary search over a sorted array with correct bounds.
  • Explain the loop invariant that keeps the search correct.
  • Derive the O(log n) complexity from repeated halving.

Overview

#

The precondition

Binary search only works when the data is sorted. If the array is not sorted, the comparison that discards half the range is meaningless.

The algorithm

snippet.txt
function binarySearch(values, target) {
  let low = 0;
  let high = values.length - 1;
  while (low <= high) {
    const mid = low + Math.floor((high - low) / 2);
    if (values[mid] === target) return mid;
    if (values[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return -1;
}

The invariant

At the top of each loop, if the target exists it lies within [low, high]. Each iteration either returns the target or shrinks the range while preserving that fact. When low passes high, the range is empty and the target is absent.

Trace

Search for 7 in [1, 3, 5, 7, 9, 11]:

lowhighmidvalues[mid]action
0525go right, low = 3
3549go left, high = 3
3337found

Three comparisons for six elements. Doubling the array adds only one comparison.

Why O(log n)

Each step halves the remaining range. After k steps the range has size n / 2^k. It reaches 1 when k is about log base 2 of n. So the loop runs O(log n) times.

The classic off-by-one

Use low <= high with high = mid - 1 and low = mid + 1, or use a half-open range [low, high) with high = mid. Mixing the two conventions is the most common binary-search bug. Also compute mid as low + (high - low) / 2 to avoid overflow in fixed-width languages.

Practice next

  • Find the first index where a value appears when duplicates are allowed.
  • Apply binary search to a rotated sorted array.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    How many comparisons does binary search need in the worst case for a sorted array of 8 elements?

    starter.javascript
    let low = 0, high = 7;
    while (low <= high) { const mid = (low + high) >> 1; /* ... */ }

    Reveal the reference answer
    reference.javascript
    Each comparison halves the range: 8, 4, 2, 1. That is 4 halvings, so at most 4 comparisons.

    Authored expected output: 4

    log base 2 of 8 is 3, and the worst case rounds up to 4 because the final single element still needs a comparison.

  2. Exercise 2Debug

    This binary search sometimes loops forever. Find and fix the bug.

    starter.javascript
    function binarySearch(values, target) {
      let low = 0;
      let high = values.length - 1;
      while (low < high) {
        const mid = Math.floor((low + high) / 2);
        if (values[mid] < target) low = mid;
        else high = mid;
      }
      return values[low] === target ? low : -1;
    }

    Reveal the reference answer
    reference.javascript
    function binarySearch(values, target) {
      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;
    }

    Authored expected output: Correct index or -1 with a terminating loop

    Setting low = mid without adding 1 can leave the range unchanged when two elements remain, so the loop never narrows.

  3. Exercise 3Explain

    State the loop invariant for binary search and explain why it guarantees correctness.

    Reveal the reference answer
    reference.text
    The invariant is that if the target exists, its index lies within [low, high]. Each iteration preserves it: moving low past mid or high before mid only discards elements that cannot be the target because the array is sorted. When the range becomes empty the target cannot exist, so returning -1 is correct.

    Authored expected output: If the target exists it stays within [low, high]; the range shrinks until empty.

    Naming the invariant turns an intuitive algorithm into a provable one.

Common misconceptions

#
  • Binary search works on any array. It requires the array to be sorted by the same order used in comparisons.
  • mid should be (low + high) / 2 without care. In fixed-width languages that can overflow; use low + (high - low) / 2.
  • The loop should stop when low == high without checking. Using low <= high guarantees the last candidate is examined.

Follow-up practice

#
  • dsa-from-zero-sorting-basics

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.