Binary search finds a target in a sorted array by inspecting the middle of the remaining candidate range. If the middle entry is smaller than , every entry to its left is also too small; if larger, every entry to its right is too large. One comparison therefore rules out many entries. Equal entries are allowed; this version returns any matching index, without promising the first occurrence.
Use indices starting at zero and inclusive endpoints . Initially , , where is the array length. While , choose
The brackets denote the floor function. Compare with : return on equality; set if ; otherwise set . If , report absence. The updates exclude the already inspected middle entry. This also handles an empty array, whose initial endpoints are . Sedgewick and Wayne specify a sorted array as input and return a matching index or for absence.[ref]
For a fully worked example, take the sorted array
Search for :
StepCandidate indicesMiddle index and valueConsequence
1, : retain .
2, : retain .
3, Return index .
For , the first two steps agree. Next retains only index ; inspecting sets . Now , so the answer is "absent" after four comparisons.
Figure 1.
Binary search retains only candidates compatible with every comparison
. Blue cells are current candidates, orange marks the middle entry, and green marks a match. Both searches use the same fifteen-entry sorted array. Details.
The loop invariant is: the array stays sorted, , and every index containing lies between and . It holds initially. The sorted array property justifies each exclusion. Returning on equality gives a match; an empty candidate range implies absence. Crucially, this loop invariant allows to be absent from the beginning.
For a nonempty range of size , an unsuccessful comparison leaves at most candidates. Thus sizes satisfy after unsuccessful comparisons. This proves termination and, for , at most middle-entry comparisons. The final singleton still needs inspection: requires one comparison, not zero. For , the bound is four. This is the halving argument behind logarithmic time complexity.[ref]
A decision tree with binary tests has at most leaves. Distinguishing possible matching positions therefore requires . This lower bound counts binary tests, whereas the bound above counts three-way comparisons.
In a nondecreasing array, the first position whose entry is at least is found by maintaining a half-open unresolved interval . Entries before are smaller than ; entries from onward are at least . Initially . At midpoint , replace by if , and otherwise replace by . Monotonicity preserves the loop invariant, and decreases. On exit is the first qualifying position, or if no such entry exists. Repeated values and endpoint cuts require no additional case.
In a nonempty rotation of a strictly increasing array, keep an inclusive interval containing its minimum. Compare its midpoint with its right endpoint. If the midpoint is larger, the minimum lies strictly to the right of the midpoint; otherwise the midpoint-to-right segment is increasing and the minimum lies at or left of the midpoint. The interval at least halves until one index remains. The cyclic predecessor of this minimum holds the maximum, so both extrema are found with comparisons. Distinctness makes the two-way comparison decisive.
Find both the lower-bound search boundary and the upper-bound search boundary of a key in a sorted array. Every entry in is at least and at most , so all are equal to . Values immediately outside this interval, when present, are strictly smaller or strictly larger; the interval is consequently maximal. An absent key gives at its insertion position. Two binary searches give total time complexity under constant-cost comparison and indexed access.
For a sorted array , find the unique boundary with . A binary search maintains , an excluded prefix , and an excluded suffix . At an interior midpoint , replace by when , and otherwise replace by . Sortedness preserves the loop invariant; the width is a decreasing loop variant. Termination at gives the boundary, including and . The time complexity is with constant-cost comparisons and indexed access. Unlike searching for , this formulation does not risk integer overflow at the largest representable key.
Suppose a candidate integer interval contains possible values and an active array segment contains exactly all occurrences from that interval, with entries. The pigeonhole principle guarantees a missing value. Split the value interval into widths and use array partitioning to obtain occurrence counts . If , retain the left side. Otherwise , so retain the right side. This works with duplicate entries because it needs only the inequality between occurrences and possible values.
Balancing the value widths gives , while the active scan length remains less than . The total work is bounded by a geometric series and logarithmic loop overhead, hence time complexity. On reaching width one, the retained occurrence count is zero, proving that the sole candidate is absent globally. This is a binary search over deficient value intervals, with local in-place array partitioning, rather than repeated full-array scans.
For distinct keys and a uniformly chosen present target, early-return binary search takes mean iterations. There are targets needing probes, so sum over depths zero through and divide by . A boundary search that always closes the interval takes exactly iterations. Their expected difference is , even though an individual shallow target can save many probes.
For a nonincreasing array, maintain indices such that entries before exceed the target and entries from onward are at most the target. Probe the middle of the half-open interval. A value above the target advances past that index; otherwise set to that index. The interval length decreases geometrically. At termination the common boundary is the first possible match, so one guarded equality test decides presence even with duplicates.
Suppose integer endpoints satisfy and . Repeatedly test an interior midpoint and replace the endpoint with its matching sign. The loop invariant is the ordered opposite-sign bracket. The positive integer width is a loop variant, and at termination . Thus an adjacent sign transition can be located in evaluations without assuming that is monotone. If extends continuously between the endpoints, the intermediate value theorem associates the sign bracket with a zero. This is different from finding the first true position of a globally monotone predicate.
For each candidate first index in a sorted array, use lower-bound search for only in the suffix starting at . A matching result is automatically at a different position. The outer loop invariant excludes all solutions whose smaller index precedes ; an unsuccessful suffix search extends this exclusion by one. Exhaustion proves absence of any pair. Searching all suffixes gives running time and constant auxiliary space. Compute the complement in a sufficiently wide type to avoid integer overflow before comparison.
For a nondecreasing sorted array and target , find the unique position such that every earlier value is below and every later value is at least . Equivalently, . Uniqueness follows because, if both satisfied the partition, would have to be both at least and below . A half-open search interval maintains an excluded prefix of smaller values and an excluded suffix of greater-or-equal values. Allowing the sentinel handles an empty array or a target beyond its last entry.

Ancestors (3)

  1. Algorithm
  2. Computer science
  3. Home

Discussion (0) New discussion

There are no discussions about this article yet.

Articles by others on the same topic (0)

There are currently no matching articles.