Algorithm Lab / Simulation

Watch binary search narrow the answer

Change the sorted input, choose a target and inspect every comparison. No animation hides the invariant.

You will learn to

  • Trace low, high and midpoint
  • Explain logarithmic search
  • Recognize the sorted-input prerequisite

Before you start

Ordered numbers and indexes

The invariant

Binary search maintains a candidate interval. If the target exists, it remains inside that interval. A smaller middle value eliminates the left half, including the middle. A larger middle value eliminates the right half. The +1 and -1 updates matter: without them a two-element interval may never shrink.

Cost and tradeoffs

Each comparison removes roughly half the remaining candidates. Search takes O(log n) comparisons and O(1) auxiliary space. Sorting first may cost more than a linear search for a one-off task. This lab requires sorted input rather than silently changing your problem.

Experiments

Find the first item, the last item and a missing item. Try one element and repeated values. With duplicates, this implementation returns one matching index, not necessarily the first. Record which interval disappears after each step.

Trace a found value and a missing value

Use [1, 3, 8, 10] and target 8 with inclusive bounds. Begin at low = 0 and high = 3. The midpoint is floor((0 + 3) / 2) = 1, whose value is 3. Because 3 is smaller than 8, move low to 2. The next midpoint is 2 and its value is 8: return index 2. Indexes begin at zero; the answer is not the number of comparisons.

For target 9, the same first comparison moves low to 2. Value 8 moves low to 3. Value 10 then moves high to 2. Now low > high, so the interval is empty and the result is -1. This is a normal absent result, not a failed algorithm. Write these bounds on paper before running the simulation.

Explain the stopping rule

The solution repeats while low <= high, returns the midpoint when its value equals the target, and otherwise excludes that midpoint with low = mid + 1 or high = mid - 1. Every unsuccessful comparison strictly shortens the candidate interval. Assigning low = mid can repeat the same midpoint forever when only two candidates remain.

This lab rejects unsorted input. Searching [8, 1, 3, 10] directly can discard the part containing the answer; sorting inside the search would change original indexes and hide its preprocessing cost. For one query, a linear scan can be a better choice. For many queries against a stable sorted collection, the preprocessing cost can be shared.

With [1, 3, 3, 3, 8], a match at index 2 is valid. To find the first occurrence, remember a match and continue searching the left interval instead of returning immediately. Compare that modification against an absent target and an all-equal array before relying on it.

Try it yourself

Enable JavaScript for this interactive activity. You can read all lesson explanations above without it.

Continue exploring