Math 2.0

Computer science Definition

Binary search

Builds on AlgorithmTotal order

Definition

Let (X,≤)(X, \le) be a totally ordered set, let a1≤a2≤⋯≤ana_1 \le a_2 \le \cdots \le a_n be a sorted array over XX, and let t∈Xt \in X be a target. Binary search is the algorithm that keeps two indices ℓ\ell and rr, starting with ℓ=1\ell = 1 and r=nr = n, and repeats the following:

  1. if ℓ>r\ell > r, stop and report that tt does not occur;
  2. otherwise let m=⌊(ℓ+r)/2⌋m = \floor{(\ell + r)/2};
  3. if am=ta_m = t, stop and return mm; if am<ta_m < t, set ℓ=m+1\ell = m + 1; if am>ta_m > t, set r=m−1r = m - 1.

Remarks

The invariant is: if tt occurs in the array, then it occurs among aℓ,…,ara_\ell, \dots, a_r. It holds at the start, and step 3 keeps it because the array is sorted. The length r−ℓ+1r - \ell + 1 of the range drops from ss to at most ⌊s/2⌋\floor{s/2} at each round, so there are at most ⌊log⁡2n⌋+1\floor{\log_2 n} + 1 rounds.

Example: for (1,3,5,7,9,11)(1, 3, 5, 7, 9, 11) and t=9t = 9: m=3m = 3 and a3=5<9a_3 = 5 < 9, so ℓ=4\ell = 4; then m=5m = 5 and a5=9a_5 = 9, so the search returns 55.

Non-example: take the unsorted array (5,1,3)(5, 1, 3) and t=5t = 5. The first round finds a2=1<5a_2 = 1 < 5 and sets ℓ=3\ell = 3. The second finds a3=3<5a_3 = 3 < 5, and the search wrongly reports that 55 does not occur. So the hypothesis that the array is sorted is needed.

Reading path

To understand this page from the ground up, read these 3 pages in order. The foundations come first.

Show the path as a graph
Each page uses the pages above it. The colour of the bar on a box shows how strong the evidence is, and the box also gives it as text. The list has the same pages.
  • no evidence level
  1. Algorithm concept
  2. Total order concept
  3. Binary search definition

Further reading

  1. Web https://en.wikipedia.org/wiki/Binary_search
About this page
Tag8YTFTSRRFS
URIm2://8YTFTSRRFS
Kinddefinition
WritingW0 stub
MSC68P10, 68W40
DefinesBinary search
UsesAlgorithm, Total order
Changed3 November 2026

Markdown · JSON · Edit on GitHub

What this page needs for W1

  • a source with a locator (0 of 1)

The writing levels say how complete the text of a page is. They do not measure its truth.

What links here

No page links to this page yet.