Binary Search

When a list is already in order, you do not need to inspect every element to find a value. Binary search examines the middle element, decides which half could still contain the target, and discards the other half. Repeating that halving finds any value in a sorted list of a million items in at most 20 probes, which is why the technique sits behind dictionary lookups, database indexes and the search functions in most standard libraries.

The halving idea

Binary search is correct only when the list is sorted in the order your comparisons assume. That ordering is what lets a single comparison rule out half the list: in an ascending list, if the middle value is smaller than the target, every value to its left is smaller as well, so none of them can be the target.


The algorithm keeps a search interval, the range of indices that might still hold the target, marked by two indices called low and high. Each iteration, or probe, does the following:

  1. Set mid to the floor of (low+high)/2(\text{low} + \text{high})/2.
  2. If the element at mid equals the target, report mid and stop.
  3. If the element at mid is smaller than the target, set low to mid + 1.
  4. If it is larger, set high to mid − 1.

When low becomes greater than high, the interval is empty and the target is not in the list.


A sorted list of nine numbers with low pointing at index 0, mid pointing at the highlighted index 4, and high pointing at index 8.


Example: To find 40 in the list shown, the first probe is index 4, which holds 28. Since 28 is less than 40, low moves to 5. The second probe is index ⌊(5+8)/2⌋=6\lfloor (5 + 8)/2 \rfloor = 6, which holds 40, so the search ends after two probes. A sequential scan from the left would have needed seven.

Writing it in code

The version below returns the index of the target, or −1 when the target is absent. Integer division // performs the floor step.


Python
def binary_search(a, target):
    low, high = 0, len(a) - 1
    while low <= high:
        mid = (low + high) // 2
        if a[mid] == target:
            return mid
        elif a[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1



How many probes it takes

Each probe either finds the target or removes the middle element and at least half of what remains. Starting from nn elements, the interval shrinks to a single element after ⌊log⁡2n⌋\lfloor \log_2 n \rfloor probes in the worst case, and one more probe settles that element. The worst case is therefore


probesworst=⌊log⁡2n⌋+1\text{probes}_{\text{worst}} = \lfloor \log_2 n \rfloor + 1


where a probe is one comparison of the middle element with the target. Sequential search, which checks elements one by one, needs up to nn probes.


List size nn

Sequential search, worst case

Binary search, worst case

10

10

4

1,000

1,000

10

1,000,000

1,000,000

20

1,000,000,000

1,000,000,000

30


Binary search runs in O(log⁡n)O(\log n) time and sequential search in O(n)O(n). A thousandfold increase in list size adds only about ten probes to binary search.



What to remember

  • Binary search requires a list sorted in the order the comparisons assume.
  • Each probe compares the middle element with the target and keeps only the half that can still contain it.
  • The loop runs while low ≤ high; an empty interval means the target is absent.
  • Worst case: ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes, compared with nn for sequential search.

Example: Tracing binary search through sorted library IDs

A school library keeps 12 book IDs in ascending order in a list ids. The search uses the standard loop: mid is the floor of (low+high)/2(\text{low} + \text{high})/2, low moves to mid + 1 when the middle value is too small, and high moves to mid − 1 when it is too large. A probe is one comparison of the middle value with the target.


Index

0

1

2

3

4

5

6

7

8

9

10

11

ID

3

8

12

17

23

29

34

41

46

55

62

70


a) Trace the search for ID 55. Give low, high and mid for each probe, and the index returned.


Start with low = 0 and high = 11.

  1. Probe 1: mid = ⌊(0+11)/2⌋\lfloor (0 + 11)/2 \rfloor = ________, which holds 29. Since 29 is less than 55, set low = 6.
  2. Probe 2: low = 6, high = 11, so mid = ⌊17/2⌋\lfloor 17/2 \rfloor = ________, which holds 46. Since 46 is less than 55, set low = 9.
  3. Probe 3: low = 9, high = 11, so mid = ⌊20/2⌋\lfloor 20/2 \rfloor = ________, which holds 62. Since 62 is greater than 55, set high = 9.
  4. Probe 4: low = high = 9, so mid = 9, which holds 55. Match.

The search returns index 9 after four probes.


b) Trace the search for ID 20, which is not in the list. State what the function returns and how many probes it uses.


Start again with low = 0 and high = 11.

  1. Probe 1: mid = 5, which holds 29. Since 29 is greater than 20, set high = ________.
  2. Probe 2: low = 0, high = 4, so mid = ⌊4/2⌋\lfloor 4/2 \rfloor = ________, which holds 12. Since 12 is less than 20, set low = 3.
  3. Probe 3: low = 3, high = 4, so mid = ⌊7/2⌋=3\lfloor 7/2 \rfloor = 3, which holds 17. Since 17 is less than 20, set low = ________.
  4. Probe 4: low = high = 4, so mid = 4, which holds 23. Since 23 is greater than 20, set high = 3.

Now low = 4 is greater than high = 3, so the interval is empty. The function returns −1 after four probes. The final value of low is where 20 would be inserted to keep the list sorted: between 17 and 23.


c) Confirm the worst case for 12 IDs, then find the worst-case number of probes for binary search and for sequential search once the library holds 5000 sorted IDs.


The worst case for binary search is ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes.


For n=12n = 12: since 23=8≤12<16=242^3 = 8 \le 12 < 16 = 2^4, ⌊log⁡212⌋\lfloor \log_2 12 \rfloor = ________, so the worst case is 3+1=43 + 1 = 4 probes. Parts a and b both used four, so they were worst-case searches.


For n=5000n = 5000: since 212=4096≤5000<8192=2132^{12} = 4096 \le 5000 < 8192 = 2^{13}, ⌊log⁡25000⌋\lfloor \log_2 5000 \rfloor = ________, so the worst case is


12+1=13 probes12 + 1 = 13 \text{ probes}


Sequential search must check every ID when the target is last or absent, so its worst case is 5000 probes. Binary search needs at most 13 probes against 5000 for sequential search.

A program uses the standard binary search for an ascending list: it probes the middle index, moves low to mid + 1 when the middle value is smaller than the target, and moves high to mid - 1 when it is larger. For which list is this program guaranteed to report correctly whether any requested value is present?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Arrange the following steps of an iterative binary search on an ascending list into the order in which the algorithm carries them out, from setting up the search to reporting a missing value.

  1. 1.

    Otherwise move low to mid + 1 or high to mid - 1, keeping the half that can still hold the target.

  2. 2.

    If the element at mid equals the target, return mid.

  3. 3.

    Set low to the first index and high to the last index of the list.

  4. 4.

    Compare the element at index mid with the target value.

  5. 5.

    While low is at most high, set mid to the floor of the average of low and high.

  6. 6.

    Once low is greater than high, report that the target is not in the list.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Match each term used to describe binary search with the description that fits it. Each description refers to a binary search running on a list of values stored at consecutive integer positions.

Match each term
A.

Running time that rises by about one step each time the list size doubles

B.

The position halfway between the current low and high indices, rounded down

C.

One comparison of the target with the element stored at the chosen position

D.

The contiguous range of positions that could still hold the target value

E.

A requirement, here that the list is sorted, which must hold before the algorithm starts

F.

The outcome when the low index passes the high index, so the target is absent

Unsuccessful search

Probe

Precondition

Logarithmic time

Midpoint

Search interval

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice