Skip to content

Binary search

finding

Level 1 of 3

Also called Half-interval search and Logarithmic search.

how it works

The idea in a few sentences and three pictures, then one search step by step.

Binary search needs the row in order, smallest first. It looks at the middle number. If that is the number wanted, it stops. If not, the order says which side the number must be on, so the other side is ruled out without a look. Then it does the same on the part that is left. Its plain name in Sebastian Bourges' books is halving (volume one, chapter 1); its formal names are binary search and bisection (volume two, chapter 14).

  • Looking for 37: 1 look, found at place 6.

    41921532243053761457518609681077118612
  • Looking for 68: 4 looks, found at place 10.

    41921532243053761457518609268104771138612
  • Looking for 90: 4 looks, not there.

    41921532243053761457518609268107711386124
  • a look, numbered in turn
  • found, ringed
  • looked at, not it
  • ruled out without a look
  • never reached
One row, three searches. Each look rules out one side unseen: the dashed boxes.
two middleslooking for 6849152230374551606877865 beforedropped6 afterkeptthe look, in neither sidethe other middle
12 numbers have two middles, places 6 and 7. This site's binary search takes the first, 37.

Looking for 68: 4 looks, found at place 10.

level 1level 2level 3level 449152230374551606877864192153224305376457518609681077118612

How many places on each level, from the top: 1, 2, 4, 5. Each level down costs one look more.

  • looked at, joined by heavy lines
  • found, ringed
The same row as a tree, each number over its own place, one level lower for each look. The search for 68 follows the heavy lines down.
At the far end: 8 moments of its 10 steps, the steps between them left for the watch page
  1. step 2 of 10

    712182331424956

    The part left runs from place 1 to place 8. Its middle number, at place 4, is 23.

    what it remembers to know where it is
    looking for
    56
    part starts at place
    1
    part ends at place
    8
    middle place
    4

    watch from here

  2. step 3 of 10

    712182331424956

    23 is smaller than 56, so 56 can only be to its right. Rule out places 1 to 4.

    what it remembers to know where it is
    looking for
    56
    part starts at place
    1
    part ends at place
    8
    middle place
    4

    watch from here

  3. step 4 of 10

    712182331424956

    The part left runs from place 5 to place 8. Its middle number, at place 6, is 42.

    what it remembers to know where it is
    looking for
    56
    part starts at place
    5
    part ends at place
    8
    middle place
    6

    watch from here

  4. step 5 of 10

    712182331424956

    42 is smaller than 56, so 56 can only be to its right. Rule out places 5 to 6.

    what it remembers to know where it is
    looking for
    56
    part starts at place
    5
    part ends at place
    8
    middle place
    6

    watch from here

  5. step 6 of 10

    712182331424956

    The part left runs from place 7 to place 8. Its middle number, at place 7, is 49.

    what it remembers to know where it is
    looking for
    56
    part starts at place
    7
    part ends at place
    8
    middle place
    7

    watch from here

  6. step 7 of 10

    712182331424956

    49 is smaller than 56, so 56 can only be to its right. Rule out 49.

    what it remembers to know where it is
    looking for
    56
    part starts at place
    7
    part ends at place
    8
    middle place
    7

    watch from here

  7. step 8 of 10

    712182331424956

    The part left runs from place 8 to place 8. Its middle number, at place 8, is 56.

    what it remembers to know where it is
    looking for
    56
    part starts at place
    8
    part ends at place
    8
    middle place
    8

    watch from here

  8. step 9 of 10

    712182331424956

    56 is the number wanted, at place 8, so it is found.

    what it remembers to know where it is
    looking for
    56
    part starts at place
    8
    part ends at place
    8
    middle place
    8

    watch from here

the steps, in plain words
  1. the part to search is the whole rowPython line 20
  2. look at the middle number of the partPython lines 12 and 13
  3. if it is the number wanted, it is foundPython lines 14 and 15
  4. if it is smaller, keep only the part to its rightPython lines 16 and 17
  5. if it is bigger, keep only the part to its leftPython line 18
  6. when no part is left, it is not in the rowPython lines 10 and 11
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def binary_search(row, target):
    """Find target in a row in order, smallest first, by halving.

    Returns its place, counted from 0 as Python counts places, or None
    when target is not in the row. Each call searches one part of the
    row, from place low to place high, and calls itself on half of it.
    """

    def search(low, high):
        if low > high:  # no part is left
            return None
        middle = (low + high) // 2  # the first of two middles
        number = row[middle]
        if number == target:  # one look: is this the number wanted?
            return middle
        if number < target:  # the same look: is it smaller?
            return search(middle + 1, high)  # keep the part to its right
        return search(low, middle - 1)  # keep the part to its left

    return search(0, len(row) - 1)  # the part to search is the whole row

how it scales

How the looks grow, from ten numbers to ten million.

Each step across or up is ten times the one before. The line for the middle number stays flat at 1 look. The other two climb slowly. 1,000 numbers take 10 looks at most: 1,000 halves to 500, 250, 125, 62, 31, 15, 7, 3 and 1, rounding down, 9 halvings, then 1 more look. 10,000 take 14. Doubling the row adds 1 look to the most. Each average point is 20 searches whose places are spread evenly over the row.

looks, ten times more at each mark up

slope 0.1102101102103104105106107slope 0.1101102101102103104105106107slope 0.1101102101102103104105106107

nn, how many numbers are in the row, ten times more at each mark to the right

  • it is bigger than every numbersolid where measured by running it; dashed where its formula carries it on to ten millionslope 0.1: ten times n, about 1 times the work
  • the number is in the row, no two equal, each place equally likely to hold the numbersolid where measured by running it; dashed where its formula carries it on to ten million
  • the number wanted is the middlesolid where measured by running it; dashed where its formula carries it on to ten million
what a dearest row costs, at a billion looks a second
nnlookstime
1,00010about 10 nanoseconds
100,00017about 17 nanoseconds
10,000,00024about 24 nanoseconds

The looks are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count the looks of binary search yourself.

Run it with Python 3.12 or later. For each size n it takes 1 to n, in
order, and prints the looks when the number wanted is the middle, the
cheapest; when it is bigger than every number, the dearest; and the exact
average when it is there, every place tried once. The plot's average points
are 20 places spread over the row, within 7 per cent of that exact average.
The counts are the same on any computer; only the time differs.
"""


class Counted:
    """A number that counts every look: a number of the row weighed against
    the number wanted. A look may ask two questions of the same two numbers,
    is it the one wanted, then is it smaller, so the same two compared twice
    in a row count as one look."""

    looks = 0
    last = None  # the two numbers of the last comparison

    def __init__(self, value):
        self.value = value

    def _look(self, other):
        pair = {id(self), id(other)}
        if pair != Counted.last:
            Counted.looks += 1
            Counted.last = pair

    def __eq__(self, other):
        self._look(other)
        return self.value == other.value

    def __lt__(self, other):
        self._look(other)
        return self.value < other.value


def binary_search(row, target):
    """Find target in a row in order, smallest first, by halving.

    Returns its place, counted from 0 as Python counts places, or None
    when target is not in the row. Each call searches one part of the
    row, from place low to place high, and calls itself on half of it.
    """

    def search(low, high):
        if low > high:  # no part is left
            return None
        middle = (low + high) // 2  # the first of two middles
        number = row[middle]
        if number == target:  # one look: is this the number wanted?
            return middle
        if number < target:  # the same look: is it smaller?
            return search(middle + 1, high)  # keep the part to its right
        return search(low, middle - 1)  # keep the part to its left

    return search(0, len(row) - 1)  # the part to search is the whole row


def count(row, target):
    """How many looks binary search makes looking for target in row."""
    Counted.looks = 0
    Counted.last = None
    binary_search([Counted(x) for x in row], Counted(target))
    return Counted.looks


if __name__ == "__main__":
    print(f"{'n':>6} {'middle':>7} {'bigger than all':>16} {'average':>9}")
    for n in [10, 100, 1000]:
        row = list(range(1, n + 1))  # in order, smallest first
        middle = row[(n - 1) // 2]
        every = sum(count(row, number) for number in row) / n
        print(f"{n:>6} {count(row, middle):>7} {count(row, n + 1):>16} {every:>9}")

best, worst and average

One search costs from 1 look to the most, ⌊log⁡2 n⌋+1\lfloor \log_2\, n \rfloor + 1, depending on where the number stands. 12 halves to 6, 3 and 1, rounding down, 3 halvings, so hh is 3, and the most is 3 and 1 more, 4.

A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestthe number wanted is the middleaveragethe number is in the row, no two equal, each place equally likely to hold the numberworstit is bigger than every number
looks1, the middle(h+1)(n+1)−2h+1+1n\frac{(h + 1)(n + 1) - 2^{h + 1} + 1}{n}, within 2 looks of the most; for 12, 37 over 12, about 3.08⌊log⁡2 n⌋+1\lfloor \log_2\, n \rfloor + 1, the most; 4 for 12
how the looks grow in each case
tight, Θ\ThetaΘ(1)\Theta(1)Θ(log⁡2 n)\Theta(\log_2\, n)Θ(log⁡2 n)\Theta(\log_2\, n)
ceiling, OOO(1)O(1)O(log⁡2 n)O(\log_2\, n)O(log⁡2 n)O(\log_2\, n)
floor, Ω\OmegaΩ(1)\Omega(1)Ω(log⁡2 n)\Omega(\log_2\, n)Ω(log⁡2 n)\Omega(\log_2\, n)

extra memory: the part's two ends and its middle beside the row. The Python's calls also wait, one inside the next, drawn below. On 12 numbers, at most 4 when the number is found, 5 when it is not.

Extra memory is the room it needs on top of the input itself, while it runs.

  • the call running, a heavy frame
  • a call waiting, a thin frame
  • looked at, the middle of its part
  • found, ringed
  • where the number would go
A call is one round: one look at the middle of one part. Unless it finds the number, it waits while the next call searches the part it kept. The parts go 12, 6, 3 and 1. For 90 one more call starts and finds no part left.
level 1level 2level 3level 4491522303745516068778634434434444444192153224305376457518609681077118612
levelplaces on itlooks eachlooks in all
1111
2224
34312
45420
in all1237

The formula on the same row, a step a line, with hh as 3:

  1. h+1=4h + 1 = 4
  2. n+1=13n + 1 = 13
  3. (h+1)(n+1)=4×13=52(h + 1)(n + 1) = 4 \times 13 = 52
  4. 2h+1=24=162^{h + 1} = 2^{4} = 16
  5. 52−16+1=3752 - 16 + 1 = 37
  6. The average: 37 looks over 12 places, about 3.08.

Each square is a number not there, with its looks: 3 squares cost 3, 10 squares cost 4.

  • a number not there
Every search on this row at once. A number not there hangs as a square under its last look. It costs 3 or 4, so not there is not always the most.
numbersmiddlethere on averagebigger than allnot there
11111
211.521 or 2
31about 1.6722
41232 or 3
512.232 or 3
61about 2.3332 or 3
71about 2.4333
81about 2.6343 or 4
Looks for 1 to 8 different numbers, each the search's own count. The average is over every place, each tried once.

where the formula comes from

Each count above, worked out in small steps. Every step names the line it uses.

Why does the middle number cost 1 look, however long the row?
  1. the move: watch the first look

    the line:
    the first look finds it\text{the first look finds it}
    • Looking for 36: 1 look, found at place 4.

      811922733641445536617
    • a look, numbered in turn
    • found, ringed
    • never reached
    36 is the middle of these 7 numbers, so the first look finds it. The other six are never reached.

    why it is allowed: The first look is at the middle, and the number there is the one wanted, so the search stops.

  2. the move: count it

    the line:
    B=1B = 1

    why it is allowed: BB is the looks when the number wanted is the middle. By line 1, one, for 7 numbers or 7 million.

  3. the move: a ceiling

    the line:
    B≤1B \le 1

    why it is allowed: By line 2.

  4. the move: read it as a bound

    the line:
    B∈O(1)B \in O(1)

    why it is allowed: By line 3, a fixed number of looks, whatever nn is.

  5. the move: a floor

    the line:
    B≥1B \ge 1

    why it is allowed: By line 2 again.

  6. the move: read it as a bound

    the line:
    B∈Ω(1)B \in \Omega(1)

    why it is allowed: By line 5.

  7. the move: ceiling and floor together

    the line:
    B∈Θ(1)B \in \Theta(1)

    why it is allowed: Lines 4 and 6 bound BB by the same: a fixed 1 look, no growth.

try it with a small nn: at n=7n = 7, line 2 gives B=1B = 1, which you can work out by hand

Why does a number bigger than every number cost ⌊log⁡2 n⌋+1\lfloor \log_2\, n \rfloor + 1 looks?
  1. the move: watch the search

    the line:
    a call looks once, thencalls itself on the part kept\begin{gathered} \text{a call looks once, then} \\ \text{calls itself on the part kept} \end{gathered}
    • Looking for 95: 4 looks, not there.

      6113221328434514765576282789391104
    • a look, numbered in turn
    • looked at, not it
    • ruled out without a look
    95 is bigger than all 10 numbers. The calls look at places 5, 8, 9 and 10, each ruling out the side before.

    why it is allowed: A call is one round: one look at the middle of its part. Unless that is the number, it rules out one side and calls itself on the other.

  2. the move: bigger than all

    the line:
    each call keeps the⌊n/2⌋ after its middle\begin{gathered} \text{each call keeps the} \\ \lfloor n / 2 \rfloor \text{ after its middle} \end{gathered}
    callits part holdsits middlekept after itlooks so far
    110place 551
    25place 822
    32place 913
    41place 1004
    50none, so no look4
    The calls for 95. Each part keeps half of the one before, rounded down, 10, 5, 2, 1, then 0.

    why it is allowed: A part of nn numbers takes the first of two middles, so half, rounded down, stand after it, ⌊n/2⌋\lfloor n / 2 \rfloor. A number bigger than all keeps that side.

  3. the move: write the calls as a cost

    the line:
    n numbers: 1 look,then the call on ⌊n/2⌋0 numbers: no look\begin{gathered} n \text{ numbers: 1 look,} \\ \text{then the call on } \lfloor n / 2 \rfloor \\ \text{0 numbers: no look} \end{gathered}

    why it is allowed: The looks on nn numbers are 1, plus the looks on ⌊n/2⌋\lfloor n / 2 \rfloor. For 10, 1 plus the looks on 5, then 1 + 1 plus those on 2, and on: line 2's last column. A cost given by the same cost at a smaller size is a recurrence.

  4. the move: unroll it

    the line:
    call j+1 holds n halvedj times, rounding down\begin{gathered} \text{call } j + 1 \text{ holds } n \text{ halved} \\ j \text{ times, rounding down} \end{gathered}
    numberlog× 2+ 14283164103.32352.322211100
    Top, numbers, each double the last; bottom, their logs, each 1 more. 10 halves to 5, 2 and 1, rounding down, 3 halvings. 10 lies between 8 and 16, so its log lies between 3 and 4, and rounds down to 3. In blue, each log rounded down, one less at each halving.

    why it is allowed: Here jj counts the halvings so far, so call 1, with jj as 0, holds the whole row. Each call looks once while its part holds a number. For 10, calls 1 to 5 hold 10, 5, 2, 1 and 0.

  5. the move: add up the calls

    the line:
    W=∑j=0h1W = \sum_{j=0}^{h} 1

    why it is allowed: WW is the looks for a number bigger than all, and hh the halvings, rounding down, that bring nn to 1. By line 4, the calls with jj from 0 to hh each look once, and the next holds none. Σ\Sigma adds the 1 after it once for each jj from 0 to hh. For 10, hh is 3.

  6. the move: use the page on halving: its count of halvings is our h

    the line:
    W=∑j=0⌊log⁡2 n⌋1W = \sum_{j=0}^{\lfloor \log_2\, n \rfloor} 1
    where does this come from?
    question 3 of the page halving and logarithmsBinary search on a row of nn numbers. At most how many looks?
    1. the move: what one look keeps

      the line:
      at most half, rounded down,of what is left\begin{gathered} \text{at most half, rounded down,} \\ \text{of what is left} \end{gathered}
      two middleslooking for 7510203040506070803 beforedropped4 afterkeptthe look, in neither sidethe other middle
      8 numbers have two middles; the table's 7 have one.
      lookstill to searchhalf, rounded downthe middlekept
      110, 20, 30, 40, 50, 60, 703.5 to 34050, 60, 70
      250, 60, 701.5 to 16070
      3700.5 to 070none
      75 is above all 7 numbers, so each look keeps the side after.

      why it is allowed: This site's binary search looks at the middle of what is left, the first of two middles, and keeps the side the wanted number must be on. From 8 it keeps 3 before or 4 after: the side after holds half, rounded down, the side before no more.

    2. the move: fewer numbers, no more looks

      the line:
      keeping a smaller part nevercosts more looks\begin{gathered} \text{keeping a smaller part never} \\ \text{costs more looks} \end{gathered}
      after lookkeeping the bigger sidekeeping the smaller side
      01010
      154
      221
      31none
      4none
      Two searches on 10 numbers. Keeping the bigger side runs out after 4 looks, the smaller after 3.

      why it is allowed: Let A always keep the bigger side, and S be any search on the same row. While S holds no more than A, it keeps at most half of its part, rounded down, so no more than A keeps. In the table, S keeps 4 to A's 5, then 1 to 2. So S runs out no later.

    3. the move: a number that keeps the bigger side

      the line:
      a number above them allkeeps the bigger side\begin{gathered} \text{a number above them all} \\ \text{keeps the bigger side} \end{gathered}

      why it is allowed: Each middle is too small, so each look keeps the side after it. That is A of line 2.

    4. the move: count that search's looks

      the line:
      ⌊log⁡2 n⌋ looks leaveone number, one morelook leaves none\begin{gathered} \lfloor \log_2\, n \rfloor \text{ looks leave} \\ \text{one number, one more} \\ \text{look leaves none} \end{gathered}

      why it is allowed: Each look halves, rounding down, so question 2 of the page halving and logarithms counts the looks to one number. 1 number takes no halving, log 0. For 7, 7 leaves 3, 3 leaves 1, and look 3 leaves none.

    5. the move: the most looks

      the line:
      B=⌊log⁡2 n⌋+1B = \lfloor \log_2\, n \rfloor + 1

      why it is allowed: Let BB be the most looks, which lines 2 to 4 count. For 7 numbers, the search for 75 takes 3, as the table at line 1 shows.

    6. the move: read it

      the line:
      one more look thanthe log rounded down\begin{gathered} \text{one more look than} \\ \text{the log rounded down} \end{gathered}

      why it is allowed: For 7 numbers, 2 and 1 more. For 16, 4 and 1 more.

    the whole page: halving and logarithms

    why it is allowed: The box counts these halvings, keeping the bigger side, so hh is ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor, and shows no search makes more looks.

  7. the move: count the calls, h for n

    the line:
    W=⌊log⁡2 n⌋+1W = \lfloor \log_2\, n \rfloor + 1
    numbershalved down to 1calls that lookhh
    88, 4, 2, 143
    1010, 5, 2, 143
    1515, 7, 3, 143
    1616, 8, 4, 2, 154
    Rounding down changes the calls' sizes, not their number. 8, 10 and 15 all take 4 calls; 16 is the first to take 5.
    where does this come from?
    question 1 of the page recurrences, unrolledEach level halves the input and does one step. What does an input of 2n2^n items cost?
    1. the move: unroll it into levels

      the line:
      level j holds one copyof 2n−j items, doing 1 step\begin{gathered} \text{level } j \text{ holds one copy} \\ \text{of } 2^{n - j} \text{ items, doing 1 step} \end{gathered}
      Binary search on 8, unrolled. Levels 1 to 3 keep the half after the look above. Dashed, that look and the numbers before it. Each level does 1 look, 4 in all.
      levelcopiesitems in eachlooks at this level
      0181
      1141
      2121
      3111
      in all4
      The levels for 8 items, 2n2^n with nn as 3.

      why it is allowed: Let jj be a level's number, 0 at the top. After jj halvings, n−jn - j twos are left, so level jj holds 2n−j2^{n - j} items. For 8, level 1 holds 4, which is 2 to the power 2. The levels stop at level nn, with no 2 left: 2 to the power 0 is 1 item. Each level's step is one look, and as in the first picture each look before the last keeps exactly the half after it.

    2. the move: add up the levels

      the line:
      H=∑j=0n1H = \sum_{j=0}^{n} 1

      why it is allowed: Let HH be the cost, the looks of every level added. Σ\Sigma, read the sum of, adds the term after it, here 1, once for each jj, from 0 under the sign to nn over it. For 8, nn is 3, so it is 1 + 1 + 1 + 1.

    3. the move: count the levels

      the line:
      H=n+1H = n + 1
      numberlog× 2+ 1833422211100
      8 halves to 4, 2 and 1. That is 3 halvings, so 4 levels and 4 looks.

      why it is allowed: The levels run from 0 to nn, which is n+1n + 1 of them, each adding 1. For 8, 4 looks.

    4. the move: read it

      the line:
      one more step thanthe halvings\begin{gathered} \text{one more step than} \\ \text{the halvings} \end{gathered}

      why it is allowed: By line 3 the cost is one more than the halvings. The page 'halving and logarithms' names that count the log to base 2 of the size. The number line at line 3 writes it under each number, 3 under the 8. Doubling to 16 items adds one halving, so one look: 5 against 4.

    the whole page: recurrences, unrolled

    why it is allowed: The calls with jj from 0 to hh are one more than hh, 1 look each. For 10, hh is 3, so WW is 1 + 1 + 1 + 1, which is 4. The box under this line counts the same shape on rows that halve exactly, its nn being this page's hh.

  8. the move: drop the rounding

    the line:
    W≤log⁡2 n+1W \le \log_2\, n + 1

    why it is allowed: By line 7, as rounding down never makes a number bigger.

  9. the move: a fixed multiple

    the line:
    W≤2 log⁡2 n for n≥2W \le 2\,\log_2\, n \text{ for } n \ge 2
    nnlog⁡2 n\log_2\, nWW2 log⁡2 n2\,\log_2\, n
    2122
    4234
    10about 3.324about 6.64
    16458
    1,000about 9.9710about 19.93
    WW stands between log⁡2 n\log_2\, n and twice it, from 2 numbers on.

    why it is allowed: From 2 numbers on, log⁡2 n\log_2\, n is at least 1, so the 1 of line 8 is at most log⁡2 n\log_2\, n.

  10. the move: read it as a bound

    the line:
    W∈O(log⁡2 n)W \in O(\log_2\, n)

    why it is allowed: By line 9, with the fixed multiple 2.

  11. the move: a floor

    the line:
    W≥log⁡2 nW \ge \log_2\, n

    why it is allowed: By line 7. Rounding down takes off less than 1, and line 7 adds 1 back.

  12. the move: read it as a bound

    the line:
    W∈Ω(log⁡2 n)W \in \Omega(\log_2\, n)

    why it is allowed: By line 11.

  13. the move: ceiling and floor together

    the line:
    W∈Θ(log⁡2 n)W \in \Theta(\log_2\, n)

    why it is allowed: Lines 10 and 12 bound WW by the same growth, log⁡2 n\log_2\, n.

try it with a small nn: at n=10n = 10, line 5 gives W=4W = 4, which you can work out by hand

Why does a number that is there cost (h+1)(n+1)−2h+1+1n\frac{(h + 1)(n + 1) - 2^{h + 1} + 1}{n} looks on average, each place as likely?
  1. the move: price one place

    the line:
    a place on level dcosts d looks\begin{gathered} \text{a place on level } d \\ \text{costs } d \text{ looks} \end{gathered}
    level 1level 2level 3512203344576451122203334445576647

    How many places on each level, from the top: 1, 2, 4. Each level down costs one look more.

    7 different numbers as a tree of looks. 33 costs 1 look, 12 and 57 cost 2, the four on the bottom cost 3.
    levelplaces on itlooks eachlooks in all
    1111
    2224
    34312
    in all717
    Added level by level, 17 looks over 7 places.

    why it is allowed: Level dd holds the places a search reaches at its look number dd; the middle is level 1. Here every number is different: copies would stop some searches sooner.

  2. the move: compare the parts

    the line:
    parts on one leveldiffer by 1 at most\begin{gathered} \text{parts on one level} \\ \text{differ by 1 at most} \end{gathered}
    level 1level 2level 3level 46132128344755627891611322132843454765576287899110

    How many places on each level, from the top: 1, 2, 4, 3. Each level down costs one look more.

    10 numbers, 1, 2 and 4 places on the full levels, then 3 of a possible 8 on the last.
    levelpartstheir sizesplaces on it
    11101
    224 and 52
    341, 2, 2 and 24
    480, 0, 0, 1, 0, 1, 0 and 13
    On 10 numbers the sizes on each level differ by 1 at most. A level holds a place for each part that is not empty.

    why it is allowed: The aim is to show only the last level can be part full. A look takes its part's middle and splits the rest into two halves, rounded down and up, which differ by 1 at most. Two parts that differ by 1 split into four that still do.

  3. the move: fill the levels

    the line:
    levels 1 to h hold 1,2,…,2h−1places, level h+1 the rest\begin{gathered} \text{levels 1 to } h \text{ hold } 1, 2, \dots, 2^{h - 1} \\ \text{places, level } h + 1 \text{ the rest} \end{gathered}

    why it is allowed: On 10, hh is 3: levels 1 to 3 are full, 1, 2 and 4 places, and level 4 holds the other 3. Level 4's parts hold 0 or 1, so there is no level 5, and only the last level can be part full. That last level is h+1h + 1, 4 for 10. No search looks more, by the worst case's lines 6 and 7. The search for the last number goes right at every look until it finds it, as one bigger than all does, so its look h+1h + 1 lands on it.

  4. the move: count level by level

    the line:
    A=1n∑j=0h(n−(1+2+⋯+2j−1))\begin{aligned} A = {} & \frac{1}{n} \sum_{j=0}^{h} \bigl(n \\ & - (1 + 2 + \dots + 2^{j - 1})\bigr) \end{aligned}
    6132128344755627891dotslevel 110level 29level 37level 43looks323413423429

    Down each column, that place's looks; across each row, the places whose search reaches that level. Both add to 29.

    The 10 numbers of line 2, a dot for each look. A row's empty cells are the places above it. Down the columns or across the rows, the dots add to 29.
    leveljjplaces aboveplaces paying
    100, none10
    2119
    321 + 2, which is 37
    431 + 2 + 4, which is 73
    in all29
    The 10 numbers again. 29 looks over 10 places is 2.9.

    why it is allowed: AA is the average, every place's looks added, over nn. Each place pays a look on every level down to its own. Here jj counts the full levels above a level, not halvings. That level is paid by every place but the 1 + 2 + ... + 2j−12^{j - 1} above it. The sum stops at 2j−12^{j - 1}, so at jj as 1 it is just 1, and at jj as 0 nothing, as the grid's rows show.

  5. the move: use the doubling sum, j for n

    the line:
    A=1n∑j=0h(n−(2j−1))A = \frac{1}{n} \sum_{j=0}^{h} \bigl(n - (2^j - 1)\bigr)
    1, 2 and 4 added a row at a time. Each total, plus the 1 hollow square, makes the next term.
    where does this come from?
    question 1 of the page doubling and halving sumsAdd 1+2+4+⋯+2n1 + 2 + 4 + \dots + 2^n. What is the total?
    1. the move: name the sum

      the line:
      S=1+2+4+⋯+2nS = 1 + 2 + 4 + \dots + 2^n

      why it is allowed: Let SS be the doubling sum up to 2n2^n. For nn as 3, it is 1 + 2 + 4 + 8.

    2. the move: double both sides

      the line:
      2S=2+4+8+⋯+2n+12S = 2 + 4 + 8 + \dots + 2^{n + 1}

      why it is allowed: Each term doubled is the next one along, and 2n2^n becomes 2n+12^{n + 1}. Doubling both sides keeps them equal. The plan: the two sums share all but their ends.

    3. the move: take line 1 away

      the line:
      2S−S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} 2S - S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Take SS from both sides of line 2. On the right, write SS out as line 1 does.

    4. the move: tidy the left side

      the line:
      S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Two lots of SS less one lot is one lot.

    5. the move: cancel what both brackets share

      the line:
      S=2n+1−1S = 2^{n + 1} - 1
      when n is 3124816
      first bracket24816
      second bracket1248
      left overtake away 116
      Line 4 when nn is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15.

      why it is allowed: Every term from 2 to 2n2^n is in both brackets and cancels, leaving 2n+12^{n + 1} less 1.

    6. the move: the terms before the last

      the line:
      1+2+⋯+2n−1=2(n−1)+1−1\begin{gathered} 1 + 2 + \dots + 2^{n - 1} \\ = 2^{(n - 1) + 1} - 1 \end{gathered}

      why it is allowed: The sum of line 5 stopping one term sooner: line 5 with n−1n - 1 for nn. For 3, it is 1 + 2 + 4. At nn as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.

    7. the move: tidy the power

      the line:
      2(n−1)+1−1=2n−12^{(n - 1) + 1} - 1 = 2^n - 1

      why it is allowed: One more than n−1n - 1 is nn. For 3, 1 + 2 + 4 is 7, one less than 8.

    8. the move: read it

      the line:
      one less thanthe next term,under twice the last\begin{gathered} \text{one less than} \\ \text{the next term,} \\ \text{under twice the last} \end{gathered}

      why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under 2n+12^{n + 1}, twice the last.

    the whole page: doubling and halving sums

    why it is allowed: The box under this line shows a doubling sum from 1 is one less than its next term, here with jj for its nn. For 3 levels above, 1 + 2 + 4 is 7, one less than 8.

  6. the move: tidy each term

    the line:
    A=1n∑j=0h((n+1)−2j)A = \frac{1}{n} \sum_{j=0}^{h} \bigl((n + 1) - 2^j\bigr)

    why it is allowed: Taking away 1 less than a number is taking the number away and adding 1 back. For 10 and 8, 10 less 7 is 10 less 8, plus 1, which is 3.

  7. the move: split the sum

    the line:
    A=1n(∑j=0h(n+1)−∑j=0h2j)A = \frac{1}{n} \Bigl(\sum_{j=0}^{h} (n + 1) - \sum_{j=0}^{h} 2^j\Bigr)

    why it is allowed: Add up the n+1n + 1s and the powers of 2 apart. For 10, 11 + 11 + 11 + 11 is 44; take away 1 + 2 + 4 + 8, which is 15: 29.

  8. the move: gather the terms

    the line:
    A=(h+1)(n+1)−(1+2+⋯+2h)nA = \frac{\begin{gathered} (h + 1)(n + 1) \\ - (1 + 2 + \dots + 2^h) \end{gathered}}{n}

    why it is allowed: jj runs from 0 to hh, so each sum has h+1h + 1 terms, which make h+1h + 1 lots of n+1n + 1, less the powers of 2.

  9. the move: use the doubling sum, h for n

    the line:
    A=(h+1)(n+1)−(2h+1−1)nA = \frac{(h + 1)(n + 1) - (2^{h + 1} - 1)}{n}
    where does this come from?
    question 1 of the page doubling and halving sumsAdd 1+2+4+⋯+2n1 + 2 + 4 + \dots + 2^n. What is the total?
    1. the move: name the sum

      the line:
      S=1+2+4+⋯+2nS = 1 + 2 + 4 + \dots + 2^n

      why it is allowed: Let SS be the doubling sum up to 2n2^n. For nn as 3, it is 1 + 2 + 4 + 8.

    2. the move: double both sides

      the line:
      2S=2+4+8+⋯+2n+12S = 2 + 4 + 8 + \dots + 2^{n + 1}

      why it is allowed: Each term doubled is the next one along, and 2n2^n becomes 2n+12^{n + 1}. Doubling both sides keeps them equal. The plan: the two sums share all but their ends.

    3. the move: take line 1 away

      the line:
      2S−S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} 2S - S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Take SS from both sides of line 2. On the right, write SS out as line 1 does.

    4. the move: tidy the left side

      the line:
      S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Two lots of SS less one lot is one lot.

    5. the move: cancel what both brackets share

      the line:
      S=2n+1−1S = 2^{n + 1} - 1
      when n is 3124816
      first bracket24816
      second bracket1248
      left overtake away 116
      Line 4 when nn is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15.

      why it is allowed: Every term from 2 to 2n2^n is in both brackets and cancels, leaving 2n+12^{n + 1} less 1.

    6. the move: the terms before the last

      the line:
      1+2+⋯+2n−1=2(n−1)+1−1\begin{gathered} 1 + 2 + \dots + 2^{n - 1} \\ = 2^{(n - 1) + 1} - 1 \end{gathered}

      why it is allowed: The sum of line 5 stopping one term sooner: line 5 with n−1n - 1 for nn. For 3, it is 1 + 2 + 4. At nn as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.

    7. the move: tidy the power

      the line:
      2(n−1)+1−1=2n−12^{(n - 1) + 1} - 1 = 2^n - 1

      why it is allowed: One more than n−1n - 1 is nn. For 3, 1 + 2 + 4 is 7, one less than 8.

    8. the move: read it

      the line:
      one less thanthe next term,under twice the last\begin{gathered} \text{one less than} \\ \text{the next term,} \\ \text{under twice the last} \end{gathered}

      why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under 2n+12^{n + 1}, twice the last.

    the whole page: doubling and halving sums

    why it is allowed: The same box, with hh for its nn, the doubling sum up to 2h2^h is 2h+12^{h + 1} less 1. For 10, hh is 3, and 1 + 2 + 4 + 8 is 15.

  10. the move: tidy

    the line:
    A=(h+1)(n+1)−2h+1+1nA = \frac{(h + 1)(n + 1) - 2^{h + 1} + 1}{n}

    why it is allowed: As in line 6. For 10, 4 times 11, less 16, plus 1, is 29, and 29 over 10 is 2.9.

  11. the move: a ceiling from the most looks

    the line:
    A≤⌊log⁡2 n⌋+1A \le \lfloor \log_2\, n \rfloor + 1

    why it is allowed: No place costs more than the most looks, by the worst case's lines 6 and 7, so neither does the average.

  12. the move: drop the rounding

    the line:
    A≤log⁡2 n+1A \le \log_2\, n + 1

    why it is allowed: By line 11, as rounding down never makes a number bigger.

  13. the move: a fixed multiple

    the line:
    A≤2 log⁡2 n for n≥2A \le 2\,\log_2\, n \text{ for } n \ge 2

    why it is allowed: From 2 numbers on, 1 is at most log⁡2 n\log_2\, n.

  14. the move: read it as a bound

    the line:
    A∈O(log⁡2 n)A \in O(\log_2\, n)

    why it is allowed: By line 13, with the fixed multiple 2.

  15. the move: a floor

    the line:
    A≥(h+1)(n+1)−2n+1nA \ge \frac{(h + 1)(n + 1) - 2n + 1}{n}

    why it is allowed: From line 10. 2h2^h is at most nn, as hh is log⁡2 n\log_2\, n rounded down, so 2h+12^{h + 1} is at most 2n2n, and taking away 2n2n takes at least as much. For 10, 8 is at most 10, so 16 is at most 20.

  16. the move: multiply out

    the line:
    A≥(h+1)n+(h+1)−2n+1nA \ge \frac{(h + 1)n + (h + 1) - 2n + 1}{n}

    why it is allowed: h+1h + 1 times n+1n + 1 is h+1h + 1 lots of nn, and h+1h + 1 more. For 10, 44 less 20, plus 1, is 25, so 2.5, under the true 2.9.

  17. the move: gather

    the line:
    A≥(h−1)n+h+2nA \ge \frac{(h - 1)n + h + 2}{n}

    why it is allowed: h+1h + 1 lots of nn, less 2 lots, leave h−1h - 1 lots, and h+1h + 1, plus 1, is h+2h + 2. For 10, 25 over 10.

  18. the move: share out

    the line:
    A≥(h−1)+h+2nA \ge (h - 1) + \frac{h + 2}{n}

    why it is allowed: Share each part of line 17 by nn. h−1h - 1 lots of nn, over nn, is h−1h - 1. For 10, 2 plus 5 over 10, which is 2.5.

  19. the move: drop the part over n

    the line:
    A≥h−1A \ge h - 1

    why it is allowed: h+2h + 2 over nn is more than 0, so dropping it leaves less. So the average is within 2 looks of the most, as 3.08 against 4 on 12 numbers.

  20. the move: a third of h + 1

    the line:
    A≥h+13 for n≥4A \ge \frac{h + 1}{3} \text{ for } n \ge 4
    hhh+13\frac{h + 1}{3}h−1h - 1
    211
    3about 1.332
    4about 1.673
    524
    From hh as 2, a third of h+1h + 1 grows by a third each step, and h−1h - 1 by 1.

    why it is allowed: The aim is a fixed multiple of log⁡2 n\log_2\, n under AA. A third, because at hh as 2 both sides are 1, and h−1h - 1 grows faster after, as the table shows. From 4 numbers on, hh is at least 2.

  21. the move: a simpler floor

    the line:
    A≥log⁡2 n3 for n≥4A \ge \frac{\log_2\, n}{3} \text{ for } n \ge 4

    why it is allowed: log⁡2 n\log_2\, n is less than h+1h + 1. At 4, line 20 gives 1, this line two thirds, and AA is 2.

  22. the move: read it as a bound

    the line:
    A∈Ω(log⁡2 n)A \in \Omega(\log_2\, n)

    why it is allowed: By line 21, with the fixed multiple a third.

  23. the move: ceiling and floor together

    the line:
    A∈Θ(log⁡2 n)A \in \Theta(\log_2\, n)

    why it is allowed: Lines 14 and 22 bound AA by the same growth, log⁡2 n\log_2\, n, with the fixed multiples 2 and a third.

try it on small inputs: over the 7 places of a row of 7 different numbers, each tried once, the average AA is about 2.43

For section 7, how many looks does linear search take on average, when the number is there?
  1. the move: how linear search pays

    the line:
    linear search, no two equal:the number at place kcosts k looks\begin{gathered} \text{linear search, no two equal:} \\ \text{the number at place } k \\ \text{costs } k \text{ looks} \end{gathered}
    • Looking for 31: 1 look, found at place 1.

      311172583224465
    • Looking for 7: 2 looks, found at place 2.

      3111722583224465
    • Looking for 58: 3 looks, found at place 3.

      31117225833224465
    • Looking for 22: 4 looks, found at place 4.

      311172258332244465
    • Looking for 46: 5 looks, found at place 5.

      3111722583322444655
    • a look, numbered in turn
    • found, ringed
    • looked at, not it
    • never reached
    Linear search on 5 numbers, each looked for in turn. The number at place 3 costs 3 looks.

    why it is allowed: Linear search looks at each number from the left and stops at the first one wanted. With no two equal, kk stands for any place, so place 3 costs 3 looks, as drawn.

  2. the move: average over the places

    the line:
    L=(1+2+⋯+n)×1nL = (1 + 2 + \dots + n) \times \frac{1}{n}
    The looks for places 1 to 5 as columns of 1 to 5. Two such staircases fill a rectangle 5 wide and 6 tall, 30 squares, so one is 15, and 15 over 5 places is 3.

    why it is allowed: LL is linear search's average, each place as likely. By line 1 the places cost 1 to nn looks, shared by nn places.

  3. the move: use the page on adding up 1 to n

    the line:
    L=n(n+1)2×1nL = \frac{n(n + 1)}{2} \times \frac{1}{n}
    where does this come from?
    question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
    1. the move: draw the sum as a staircase

      the line:
      S=1+2+⋯+nS = 1 + 2 + \dots + n

      why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

    2. the move: take two staircases

      the line:
      2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

      why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

    3. the move: fit them into a rectangle

      the line:
      2S=n(n+1)2S = n(n + 1)
      Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

      why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

    4. the move: halve both sides

      the line:
      S=n(n+1)2S = \frac{n(n + 1)}{2}

      why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

    the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

    why it is allowed: The box shows two staircases fill nn by n+1n + 1, so one is half that. For 5, 5 times 6, halved, is 15.

  4. the move: share by n

    the line:
    L=n+12L = \frac{n + 1}{2}

    why it is allowed: The nn on top and the nn underneath cancel. For 5, 15 over 5 is 3, and 6 over 2 is 3 too.

try it with a small nn: at n=5n = 5, line 2 gives L=3L = 3, which you can work out by hand

count it yourself

Count every look for 95 in 6, 13, 21, 28, 34, 47, 55, 62, 78, 91.

6, 13, 21, 28, 34, 47, 55, 62, 78, 91; 95, every step written down
stepwhat happenslooks
1There are 10 numbers in a row, in order, smallest first. Look for 95, starting with the whole row.0
2The part left runs from place 1 to place 10. Its middle number, at place 5, is 34.1
334 is smaller than 95, so 95 can only be to its right. Rule out places 1 to 5.1
4The part left runs from place 6 to place 10. Its middle number, at place 8, is 62.2
562 is smaller than 95, so 95 can only be to its right. Rule out places 6 to 8.2
6The part left runs from place 9 to place 10. Its middle number, at place 9, is 78.3
778 is smaller than 95, so 95 can only be to its right. Rule out 78.3
8The part left runs from place 10 to place 10. Its middle number, at place 10, is 91.4
991 is smaller than 95, so 95 can only be to its right. Rule out 91.4
10No part is left, so 95 is not in the row.4
11Done after 4 looks.4

In all, 4 looks. The formula from section 4, ⌊log⁡2 n⌋+1\lfloor \log_2\, n \rfloor + 1, gives W=4W = 4 at n=10n = 10: the same.

where you meet it

Most programming languages hand you binary search ready made. Python's and Java's are worked on the row 7, 15, 15, 15, 26, 38, 41, drawn after them.

  • Python's bisect

    On a list in order, bisect_left(row, x) gives the index, counted from 0, equal to how many numbers are smaller than x, and bisect_right how many are no bigger. Neither stops early. So bisect_left keeps halving left to the first copy, index 1, place 2, where this page's search stops at place 4.

    source: the Python documentation, bisect, Array bisection algorithm (opens in a new tab); CPython's Lib/bisect.py

  • Java's Arrays.binarySearch

    On an array in order it gives the number's index, counted from 0. When the number is not there, it gives minus the index it would have, less 1, so for 30, minus 5, less 1, is minus 6. With copies, it may give the index of any of them.

    source: the Java SE 21 API documentation (opens in a new tab), class java.util.Arrays, method binarySearch

  • git bisect

    A commit is a saved version of a program; checking one takes a build of it, then a test. To find the commit that brought in a fault, git has you test one halfway between a good one and a bad one. It then keeps the half holding the fault. Volume two, chapter 14 of Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, puts it as 'two thousand commits, eleven builds'. 2,000 lies between 1,024 and 2,048, 2 to the power 10 and 2 to the power 11, so with nn as 2,000, ⌊log⁡2 n⌋+1\lfloor \log_2\, n \rfloor + 1 is 10 and 1 more, 11.

    source: the git documentation, git-bisect (opens in a new tab)

  • Looking for 15: 1 look, found at place 4.

    711521531541265386417
  • a look, numbered in turn
  • found, ringed
  • never reached
15 stands three times. This page's search stops at its first look, the middle copy, index 3. bisect_left lands at index 1, bisect_right at index 4.
askedanswerwhy
binary_search(row, 15)3index 3, place 4 on this page, the middle copy
bisect_left(row, 15)1index 1, place 2, the first copy
bisect_right(row, 15)4index 4, just after the last copy
binary_search(row, 30)Nonenot there
bisect_left(row, 30)5index 5, where 30 would go, after 26
binarySearch for 30, in Javaminus 6minus 5, less 1
Asking for 15 and 30, the row kept as a list called row.

what is used instead

Linear search is used on a row in no order searched once, since putting a row in order costs more than one linear search. To ask only whether a number is there, a dictionary, a store that goes straight to a key, such as Python's dict, answers in about one look. It cannot give the next bigger number, as volume two, chapter 14 of Sebastian Bourges' books notes. Volume one, chapter 1 of the same books gives the rule. "Use binary search when the data is already in order and you will search it more than a handful of times".

how it compares

Binary search beside three other searches. Each counts its looks.

wayhow it looksneeds the row in ordermost looks on 12 numbersthere, on average, on 12reach for it when
linear searchone number at a time, from the leftno126.5the row is short, or in no order and searched once
binary searchthe middle of what is left, keeping one sideyes4about 3.08the row is in order and searched many times
jump searcha block at a time, then through the blockyes74.5the row is in order but can only be read from the front, as on tape
interpolation searchguesses the place from the number's sizeyes1 spread evenly, 10 bunched1 spread evenly, about 5.42 bunchedthe row is long, in order, and close to equal steps
Each count is that search's own run on 12 numbers in order. The most is over every number from 1 to 99, the average over the 12 that are there. One row is spread evenly, 8, 16, 24 and on to 96; one is bunched, 1 to 11 then 99. The last column's first two rows follow Sebastian Bourges' books (volume one, chapter 1).
102104106101102103104105106107101102103104105106107101102103104105106107
  • binary search at most, ⌊log⁡2 n⌋+1\lfloor \log_2\, n \rfloor + 1
  • binary search on average, (h+1)(n+1)−2h+1+1n\frac{(h + 1)(n + 1) - 2^{h + 1} + 1}{n}
  • linear search on average, n+12\frac{n + 1}{2}
Each average looks for the number at every place in turn. Doubling the row nearly doubles linear search's looks but adds about 1 to binary search's (Sebastian Bourges' books, volume one, chapter 1). At a million numbers, 500,000.5 against about 18.95.

race them on one row of your own