Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Binary search finds a value—or a boundary—in a sorted sequence by repeatedly ruling out half of the remaining candidates. Its correctness depends on two things: the input order must support the comparisons, and the code must maintain a precise definition of which indices are still possible.

What binary search does

Suppose an array A is sorted in ascending order and you want to find target x. Binary search checks a middle element. If that value is too small, sorted order proves that the midpoint and everything before it cannot equal x. If it is too large, the midpoint and everything after it can be excluded. If it is equal, the search has found a match.

The key is not simply checking the middle. It is using the ordering to prove that a whole portion of the sequence cannot contain the answer. On an unsorted sequence, a midpoint comparison gives no such proof: a smaller value could still occur on either side.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why the sequence must be sorted

The sequence must be ordered according to the same comparison used by the search. For example, if the search tests whether values are less than x, the input must be sorted under that less-than ordering. Otherwise, the result of a comparison at one position cannot justify discarding the positions before or after it.

#1 Best Overall
Sale
Introduction to Algorithms, fourth edition
  • color: White
  • INTRODUCTION TO ALGORITHMS, FOURTH EDITION

For an exact-match search, each comparison either finds x or eliminates the midpoint and one side. When no candidates remain, the target is absent. This absence result is meaningful only because the sorted-order precondition made every discarded region safe to exclude.

Use an interval convention to prevent off-by-one errors

One clear convention is a half-open interval [L, R). It includes index L and excludes index R, so the candidate indices are L through R − 1. For an array of length n, initialize L = 0 and R = n. The range is empty exactly when L = R.

Maintain the bounds 0 ≤ L ≤ R ≤ n. While L < R, choose m = L + floor((R − L) / 2). This midpoint is inside the active range. The updates follow from the definition of the candidates:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • If A[m] < x, indices through m cannot contain an exact match, so set L = m + 1.
  • If A[m] > x, indices from m onward cannot contain an exact match, so set R = m.
  • If A[m] = x, return m.

When the loop ends with L = R, no candidate remains, so return a not-found result. The loop condition and updates belong together: changing the interval convention requires changing the termination and boundary logic too.

Why the loop terminates

Each non-matching comparison makes the interval strictly smaller. If the midpoint value is too small, the new lower bound is m + 1; if it is too large, the new upper bound is m. The interval therefore cannot remain the same from one iteration to the next and eventually becomes empty or produces a match.

An inclusive interval is also valid

Another common formulation keeps both endpoints inside the candidate range and uses a condition such as low ≤ high. It needs different updates and termination details from the half-open version. Do not mix its loop condition with half-open updates: first state what the endpoints mean, then derive each comparison’s update from that meaning.

Rank #3
Sale
Algorithm Design
  • Used Book in Good Condition

What binary search returns when values repeat

An exact-match routine may return any matching occurrence unless its contract promises a particular one. It does not necessarily find the first duplicate. If the required result is a boundary, define that task separately:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Lower bound: the first position whose value is not less than x.
  • Upper bound: the first position whose value is greater than x.

These are searches for a transition in a monotone condition, not merely a search for an equal value. Their invariants must describe which positions could still be the boundary, and their return value can be a valid insertion position even when x is absent. A routine’s name or a successful example does not establish duplicate behavior; check its stated contract.

Why midpoint arithmetic can overflow

The expression (low + high) / 2 can overflow even when both indices are valid. In a 2006 post, Google engineer Joshua Bloch described a Java implementation where adding sufficiently large nonnegative indices exceeded the largest positive signed 32-bit integer, producing an invalid negative midpoint. He said the particular bug could affect arrays with 2^30 elements or more; that threshold applies to the described implementation, not universally to every language or data structure. Bloch’s explanation proposes low + ((high - low) / 2) for that nonnegative-index setting.

That alternative avoids summing the two large indices when the stated range assumptions hold. In other settings, verify that the subtraction and arithmetic are safe under the language’s integer rules. C and C++ have their own signed-overflow behavior; a shift or unsigned conversion should not be copied across languages without checking what it guarantees. Choose an expression whose safety follows from the actual index range and the language semantics.

How halving produces logarithmic work

Each unsuccessful comparison leaves roughly half as many candidates as before. After k levels, the remaining range is about n / 2k; it takes roughly log₂ n levels to reduce that range to one candidate. Thus binary search has an O(log n) worst-case comparison bound, as described in Carnegie Mellon University’s 2014 course notes. Doubling the input size adds roughly one comparison level. This counts comparisons for the halving search; it is not a benchmark of a particular implementation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check the contract, invariant, and progress

Binary search is short, but correctness depends on more than the midpoint formula. Before relying on an implementation, check:

  • Precondition: Is the input sorted according to the comparison being used?
  • Interval: Are both endpoints included, or is the upper endpoint excluded?
  • Invariant: Does the code preserve a precise statement of where the answer can still be, and what has already been ruled out?
  • Progress: Does every non-matching comparison make the active range smaller?
  • Result contract: What does it return when the target is absent? If duplicates exist, does it return any match, the first, the last, or a boundary?
  • Arithmetic: Can the midpoint expression overflow for the supported index range and language?

The INRIA Toccata/Why3 binary-search example illustrates how a formal specification can state sortedness, what a returned index guarantees, what not-found means, and a decreasing measure for termination. The invariant is a practical way to connect the algorithm’s intended behavior to its loop updates.

Binary search has a long history of subtle mistakes. Carnegie Mellon’s 2014 notes quote Jon Bentley’s account that “only about ten percent of professional programmers were able to get this small program right” in a reported classroom exercise. That is a historical classroom report, not a current representative measure of programmers. The same notes quote Bentley’s view that understanding loop invariants is central to composing correct programs.

Further reading

Jon Bentley’s Programming Pearls, Second Edition, includes “The Challenge of Binary Search” in its chapter on writing correct programs, according to the publisher’s contents page. It is a broader book about programming, not a book solely about binary search.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

SaleBestseller No. 1
Introduction to Algorithms, fourth edition
Introduction to Algorithms, fourth edition
color: White; INTRODUCTION TO ALGORITHMS, FOURTH EDITION
$99.47
SaleBestseller No. 2
SaleBestseller No. 3
Algorithm Design
Algorithm Design
Used Book in Good Condition
$223.93
SaleBestseller No. 4

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.