Binary 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.
Looking for 68: 4 looks, found at place 10.
Looking for 90: 4 looks, not there.
- a look, numbered in turn
- found, ringed
- looked at, not it
- ruled out without a look
- never reached
Looking for 68: 4 looks, found at place 10.
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
step 2 of 10
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
step 3 of 10
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
step 4 of 10
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
step 5 of 10
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
step 6 of 10
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
step 7 of 10
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
step 8 of 10
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
step 9 of 10
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
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- the part to search is the whole rowPython line 20
- look at the middle number of the partPython lines 12 and 13
- if it is the number wanted, it is foundPython lines 14 and 15
- if it is smaller, keep only the part to its rightPython lines 16 and 17
- if it is bigger, keep only the part to its leftPython line 18
- 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
, 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
| looks | time | |
|---|---|---|
| 1,000 | 10 | about 10 nanoseconds |
| 100,000 | 17 | about 17 nanoseconds |
| 10,000,000 | 24 | about 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, , depending on where the number stands. 12 halves to 6, 3 and 1, rounding down, 3 halvings, so 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.
| bestthe number wanted is the middle | averagethe number is in the row, no two equal, each place equally likely to hold the number | worstit is bigger than every number | |
|---|---|---|---|
| looks | 1, the middle | , within 2 looks of the most; for 12, 37 over 12, about 3.08 | , the most; 4 for 12 |
| how the looks grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
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.
Looking for 68: 4 calls open at once.
Looking for 90: 5 calls open at once.
- 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
| level | places on it | looks each | looks in all |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 4 |
| 3 | 4 | 3 | 12 |
| 4 | 5 | 4 | 20 |
| in all | 12 | 37 |
The formula on the same row, a step a line, with as 3:
- 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
| numbers | middle | there on average | bigger than all | not there |
|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 1.5 | 2 | 1 or 2 |
| 3 | 1 | about 1.67 | 2 | 2 |
| 4 | 1 | 2 | 3 | 2 or 3 |
| 5 | 1 | 2.2 | 3 | 2 or 3 |
| 6 | 1 | about 2.33 | 3 | 2 or 3 |
| 7 | 1 | about 2.43 | 3 | 3 |
| 8 | 1 | about 2.63 | 4 | 3 or 4 |
where the formula comes from
Each count above, worked out in small steps. Every step names the line it uses.
the move: watch the first look
the line:Looking for 36: 1 look, found at place 4.
- 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.
the move: count it
the line:why it is allowed: is the looks when the number wanted is the middle. By line 1, one, for 7 numbers or 7 million.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 3, a fixed number of looks, whatever is.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2 again.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 4 and 6 bound by the same: a fixed 1 look, no growth.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: watch the search
the line:Looking for 95: 4 looks, not there.
- 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.
the move: bigger than all
the line:call its part holds its middle kept after it looks so far 1 10 place 5 5 1 2 5 place 8 2 2 3 2 place 9 1 3 4 1 place 10 0 4 5 0 none, so no look 4 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 numbers takes the first of two middles, so half, rounded down, stand after it, . A number bigger than all keeps that side.
guess it, thenthe move: write the calls as a cost
the line:why it is allowed: The looks on numbers are 1, plus the looks on . 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.
guess it, thenthe move: unroll it
the line: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 counts the halvings so far, so call 1, with 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.
guess it, thenthe move: add up the calls
the line:why it is allowed: is the looks for a number bigger than all, and the halvings, rounding down, that bring to 1. By line 4, the calls with from 0 to each look once, and the next holds none. adds the 1 after it once for each from 0 to . For 10, is 3.
guess it, thenthe move: use the page on halving: its count of halvings is our h
the line:where does this come from?
question 3 of the page halving and logarithmsBinary search on a row of numbers. At most how many looks? the move: what one look keeps
the line:8 numbers have two middles; the table's 7 have one. look still to search half, rounded down the middle kept 1 10, 20, 30, 40, 50, 60, 70 3.5 to 3 40 50, 60, 70 2 50, 60, 70 1.5 to 1 60 70 3 70 0.5 to 0 70 none 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.
the move: fewer numbers, no more looks
the line:after look keeping the bigger side keeping the smaller side 0 10 10 1 5 4 2 2 1 3 1 none 4 none 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.
the move: a number that keeps the bigger side
the line:why it is allowed: Each middle is too small, so each look keeps the side after it. That is A of line 2.
the move: count that search's looks
the line: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.
the move: the most looks
the line:why it is allowed: Let 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.
the move: read it
the line:why it is allowed: For 7 numbers, 2 and 1 more. For 16, 4 and 1 more.
why it is allowed: The box counts these halvings, keeping the bigger side, so is , and shows no search makes more looks.
guess it, thenthe move: count the calls, h for n
the line:numbers halved down to 1 calls that look 8 8, 4, 2, 1 4 3 10 10, 5, 2, 1 4 3 15 15, 7, 3, 1 4 3 16 16, 8, 4, 2, 1 5 4 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 items cost? the move: unroll it into levels
the line: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. level copies items in each looks at this level 0 1 8 1 1 1 4 1 2 1 2 1 3 1 1 1 in all 4 The levels for 8 items, with as 3. why it is allowed: Let be a level's number, 0 at the top. After halvings, twos are left, so level holds items. For 8, level 1 holds 4, which is 2 to the power 2. The levels stop at level , 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.
the move: add up the levels
the line:why it is allowed: Let be the cost, the looks of every level added. , read the sum of, adds the term after it, here 1, once for each , from 0 under the sign to over it. For 8, is 3, so it is 1 + 1 + 1 + 1.
the move: count the levels
the line: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 , which is of them, each adding 1. For 8, 4 looks.
the move: read it
the line: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.
why it is allowed: The calls with from 0 to are one more than , 1 look each. For 10, is 3, so is 1 + 1 + 1 + 1, which is 4. The box under this line counts the same shape on rows that halve exactly, its being this page's .
guess it, thenthe move: drop the rounding
the line:why it is allowed: By line 7, as rounding down never makes a number bigger.
guess it, thenthe move: a fixed multiple
the line:2 1 2 2 4 2 3 4 10 about 3.32 4 about 6.64 16 4 5 8 1,000 about 9.97 10 about 19.93 stands between and twice it, from 2 numbers on. why it is allowed: From 2 numbers on, is at least 1, so the 1 of line 8 is at most .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: By line 7. Rounding down takes off less than 1, and line 7 adds 1 back.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 10 and 12 bound by the same growth, .
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: price one place
the line: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. level places on it looks each looks in all 1 1 1 1 2 2 2 4 3 4 3 12 in all 7 17 Added level by level, 17 looks over 7 places. why it is allowed: Level holds the places a search reaches at its look number ; the middle is level 1. Here every number is different: copies would stop some searches sooner.
the move: compare the parts
the line: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. level parts their sizes places on it 1 1 10 1 2 2 4 and 5 2 3 4 1, 2, 2 and 2 4 4 8 0, 0, 0, 1, 0, 1, 0 and 1 3 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.
guess it, thenthe move: fill the levels
the line:why it is allowed: On 10, 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 , 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 lands on it.
guess it, thenthe move: count level by level
the line: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. level places above places paying 1 0 0, none 10 2 1 1 9 3 2 1 + 2, which is 3 7 4 3 1 + 2 + 4, which is 7 3 in all 29 The 10 numbers again. 29 looks over 10 places is 2.9. why it is allowed: is the average, every place's looks added, over . Each place pays a look on every level down to its own. Here counts the full levels above a level, not halvings. That level is paid by every place but the 1 + 2 + ... + above it. The sum stops at , so at as 1 it is just 1, and at as 0 nothing, as the grid's rows show.
guess it, thenthe move: use the doubling sum, j for n
the line: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 . What is the total? the move: name the sum
the line:why it is allowed: Let be the doubling sum up to . For as 3, it is 1 + 2 + 4 + 8.
the move: double both sides
the line:why it is allowed: Each term doubled is the next one along, and becomes . Doubling both sides keeps them equal. The plan: the two sums share all but their ends.
the move: take line 1 away
the line:why it is allowed: Take from both sides of line 2. On the right, write out as line 1 does.
the move: tidy the left side
the line:why it is allowed: Two lots of less one lot is one lot.
the move: cancel what both brackets share
the line:when n is 3 1 2 4 8 16 first bracket 2 4 8 16 second bracket 1 2 4 8 left over take away 1 16 Line 4 when is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15. why it is allowed: Every term from 2 to is in both brackets and cancels, leaving less 1.
the move: the terms before the last
the line:why it is allowed: The sum of line 5 stopping one term sooner: line 5 with for . For 3, it is 1 + 2 + 4. At as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.
the move: tidy the power
the line:why it is allowed: One more than is . For 3, 1 + 2 + 4 is 7, one less than 8.
the move: read it
the line: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 , twice the last.
why it is allowed: The box under this line shows a doubling sum from 1 is one less than its next term, here with for its . For 3 levels above, 1 + 2 + 4 is 7, one less than 8.
guess it, thenthe move: tidy each term
the line: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.
guess it, thenthe move: split the sum
the line:why it is allowed: Add up the s and the powers of 2 apart. For 10, 11 + 11 + 11 + 11 is 44; take away 1 + 2 + 4 + 8, which is 15: 29.
guess it, thenthe move: gather the terms
the line:why it is allowed: runs from 0 to , so each sum has terms, which make lots of , less the powers of 2.
guess it, thenthe move: use the doubling sum, h for n
the line:where does this come from?
question 1 of the page doubling and halving sumsAdd . What is the total? the move: name the sum
the line:why it is allowed: Let be the doubling sum up to . For as 3, it is 1 + 2 + 4 + 8.
the move: double both sides
the line:why it is allowed: Each term doubled is the next one along, and becomes . Doubling both sides keeps them equal. The plan: the two sums share all but their ends.
the move: take line 1 away
the line:why it is allowed: Take from both sides of line 2. On the right, write out as line 1 does.
the move: tidy the left side
the line:why it is allowed: Two lots of less one lot is one lot.
the move: cancel what both brackets share
the line:when n is 3 1 2 4 8 16 first bracket 2 4 8 16 second bracket 1 2 4 8 left over take away 1 16 Line 4 when is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15. why it is allowed: Every term from 2 to is in both brackets and cancels, leaving less 1.
the move: the terms before the last
the line:why it is allowed: The sum of line 5 stopping one term sooner: line 5 with for . For 3, it is 1 + 2 + 4. At as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.
the move: tidy the power
the line:why it is allowed: One more than is . For 3, 1 + 2 + 4 is 7, one less than 8.
the move: read it
the line: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 , twice the last.
why it is allowed: The same box, with for its , the doubling sum up to is less 1. For 10, is 3, and 1 + 2 + 4 + 8 is 15.
guess it, thenthe move: tidy
the line: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.
guess it, thenthe move: a ceiling from the most looks
the line: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.
guess it, thenthe move: drop the rounding
the line:why it is allowed: By line 11, as rounding down never makes a number bigger.
guess it, thenthe move: a fixed multiple
the line:why it is allowed: From 2 numbers on, 1 is at most .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 13, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: From line 10. is at most , as is rounded down, so is at most , and taking away takes at least as much. For 10, 8 is at most 10, so 16 is at most 20.
guess it, thenthe move: multiply out
the line:why it is allowed: times is lots of , and more. For 10, 44 less 20, plus 1, is 25, so 2.5, under the true 2.9.
guess it, thenthe move: gather
the line:why it is allowed: lots of , less 2 lots, leave lots, and , plus 1, is . For 10, 25 over 10.
guess it, thenthe move: share out
the line:why it is allowed: Share each part of line 17 by . lots of , over , is . For 10, 2 plus 5 over 10, which is 2.5.
guess it, thenthe move: drop the part over n
the line:why it is allowed: over 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.
guess it, thenthe move: a third of h + 1
the line:2 1 1 3 about 1.33 2 4 about 1.67 3 5 2 4 From as 2, a third of grows by a third each step, and by 1. why it is allowed: The aim is a fixed multiple of under . A third, because at as 2 both sides are 1, and grows faster after, as the table shows. From 4 numbers on, is at least 2.
guess it, thenthe move: a simpler floor
the line:why it is allowed: is less than . At 4, line 20 gives 1, this line two thirds, and is 2.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 21, with the fixed multiple a third.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 14 and 22 bound by the same growth, , with the fixed multiples 2 and a third.
guess it, then
try it on small inputs: over the 7 places of a row of 7 different numbers, each tried once, the average is about 2.43
the move: how linear search pays
the line:Looking for 31: 1 look, found at place 1.
Looking for 7: 2 looks, found at place 2.
Looking for 58: 3 looks, found at place 3.
Looking for 22: 4 looks, found at place 4.
Looking for 46: 5 looks, found at place 5.
- 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, stands for any place, so place 3 costs 3 looks, as drawn.
the move: average over the places
the line: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: is linear search's average, each place as likely. By line 1 the places cost 1 to looks, shared by places.
guess it, thenthe move: use the page on adding up 1 to n
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: The box shows two staircases fill by , so one is half that. For 5, 5 times 6, halved, is 15.
guess it, thenthe move: share by n
the line:why it is allowed: The on top and the underneath cancel. For 5, 15 over 5 is 3, and 6 over 2 is 3 too.
guess it, then
try it with a small : at , line 2 gives , 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.
| step | what happens | looks |
|---|---|---|
| 1 | There are 10 numbers in a row, in order, smallest first. Look for 95, starting with the whole row. | 0 |
| 2 | The part left runs from place 1 to place 10. Its middle number, at place 5, is 34. | 1 |
| 3 | 34 is smaller than 95, so 95 can only be to its right. Rule out places 1 to 5. | 1 |
| 4 | The part left runs from place 6 to place 10. Its middle number, at place 8, is 62. | 2 |
| 5 | 62 is smaller than 95, so 95 can only be to its right. Rule out places 6 to 8. | 2 |
| 6 | The part left runs from place 9 to place 10. Its middle number, at place 9, is 78. | 3 |
| 7 | 78 is smaller than 95, so 95 can only be to its right. Rule out 78. | 3 |
| 8 | The part left runs from place 10 to place 10. Its middle number, at place 10, is 91. | 4 |
| 9 | 91 is smaller than 95, so 95 can only be to its right. Rule out 91. | 4 |
| 10 | No part is left, so 95 is not in the row. | 4 |
| 11 | Done after 4 looks. | 4 |
In all, 4 looks. The formula from section 4, , gives at : 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 as 2,000, 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.
- a look, numbered in turn
- found, ringed
- never reached
| asked | answer | why |
|---|---|---|
| binary_search(row, 15) | 3 | index 3, place 4 on this page, the middle copy |
| bisect_left(row, 15) | 1 | index 1, place 2, the first copy |
| bisect_right(row, 15) | 4 | index 4, just after the last copy |
| binary_search(row, 30) | None | not there |
| bisect_left(row, 30) | 5 | index 5, where 30 would go, after 26 |
| binarySearch for 30, in Java | minus 6 | minus 5, less 1 |
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.
| way | how it looks | needs the row in order | most looks on 12 numbers | there, on average, on 12 | reach for it when |
|---|---|---|---|---|---|
| linear search | one number at a time, from the left | no | 12 | 6.5 | the row is short, or in no order and searched once |
| binary search | the middle of what is left, keeping one side | yes | 4 | about 3.08 | the row is in order and searched many times |
| jump search | a block at a time, then through the block | yes | 7 | 4.5 | the row is in order but can only be read from the front, as on tape |
| interpolation search | guesses the place from the number's size | yes | 1 spread evenly, 10 bunched | 1 spread evenly, about 5.42 bunched | the row is long, in order, and close to equal steps |
- binary search at most,
- binary search on average,
- linear search on average,