Home › Theme B › B2 › B2.4 › B2.4.2

B2.4.2 Linear and binary search

SL + HLCommand terms: Construct, Trace

1. Search race on a sorted shelf

The same 16 titles, in alphabetical order. Each press of Next makes one comparison in each algorithm. Linear search checks one book after another; binary search checks the middle and throws away the half that cannot contain the target.

Find:
Linear search   comparisons: 0
Binary search   comparisons: 0

2. Search lab: big lists, and what if it is not sorted?

Choose the list size and the target book ID, then step or run. Switch to an unsorted list and watch binary search fail: it relies on order to know which half to discard.

Algorithm: LinearBinary   List: sortedunsorted
n = 64   target ID:
  comparisons: 0
Press Step or Run.

3. Be the binary search

The 100 books are sorted by accession number. Find the one you are asked for by clicking spines. After each click you are told whether the target is earlier or later. Can you always do it in 7 clicks or fewer?

Find book   clicks: 0
Click any spine.

4. The phone directory problem

The school directory lists 2,000 people sorted by name. Finding a number from a name is different from finding a name from a number. Run both, then decide whether sorting a second copy by number is worth it.

Run a task.

Is a second copy sorted by number worth it?

Reverse lookups per day: 20

5. Construct a binary search trace table

Complete one row per pass of the loop: low, high, mid = (low + high) // 2, items[mid] and what happens next.

items =   target =

6. Flip-card deck

Click to flip. Say the answer before you flip.

7. Linear or binary?

Which search suits the situation? Streaks of 3+ score double.

Round 0/10Score 0Streak 0Best 0
Press start!

8. 45-second speed round: mid and maximum comparisons

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 4, task 2. The catalogue is kept sorted by title. Write a linear search and a binary search that both report how many comparisons they made, then decide which search to use when the librarian scans an ISBN instead of typing a title.

Expected output

(0, 1) (999, 1000) (-1, 1000) (0, 9) (999, 10) (500, 9) (-1, 10) Emma None

Think about it

(1) Which line of the output shows linear search's best case, and which its worst case? (2) Why can find_title_by_isbn not use binary search on this catalogue? (3) The catalogue grows to 1,000,000 titles. Predict both searches' worst-case comparisons.

Check my code

    Next task (B2.4.3): keep the catalogue sorted, with bubble sort and selection sort.

    Practical tasks

    Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    Task 1: Linear search for all matches

    Write find_all(items, target) that returns a list of every index where target appears, using a linear search. Then answer: how many comparisons does it always make for a list of n items?

    Starter file (write your code where it says pass # your code here):

    File: b2_4_2_average.py
    def find_all(items, target):
        pass  # your code here
    
    # ---- tests ----
    books = ["Dune", "Emma", "Dune", "Kim", "Dune"]
    print(find_all(books, "Dune"), find_all(books, "Holes"))
    

    Expected output when your code is correct:

    [0, 2, 4] []
    Hint
    Do not stop at the first match.
    Model solution

    It must check every item to find all matches, so it always makes n comparisons: O(n), with no early exit.

    File: b2_4_2_average_solution.py
    def find_all(items, target):
        positions = []
        for i in range(len(items)):
            if items[i] == target:
                positions.append(i)
        return positions
    
    # ---- tests ----
    books = ["Dune", "Emma", "Dune", "Kim", "Dune"]
    print(find_all(books, "Dune"), find_all(books, "Holes"))
    
    Moderate

    Task 2: Binary search with a comparison counter

    Write an iterative binary_search(items, target) on a sorted list that returns (index, comparisons), with index −1 if not found. Search a sorted list of 1 000 000 numbers and compare the counts with log₂(1 000 000) ≈ 20.

    Starter file (write your code where it says pass # your code here):

    File: b2_4_2_moderate.py
    def binary_search(items, target):
        pass  # your code here
    
    # ---- tests ----
    data = list(range(0, 2000000, 2))
    print(binary_search(data, 1234566))
    print(binary_search(data, 7))
    print(binary_search([5], 5), binary_search([], 5))
    

    Expected output when your code is correct:

    (617283, 20)
    (-1, 20)
    (0, 1) (-1, 0)
    Hint
    Count one comparison for each time you look at items[mid].
    Model solution
    File: b2_4_2_moderate_solution.py
    def binary_search(items, target):
        low, high = 0, len(items) - 1
        comparisons = 0
        while low <= high:
            mid = (low + high) // 2
            comparisons += 1
            if items[mid] == target:
                return mid, comparisons
            elif items[mid] < target:
                low = mid + 1
            else:
                high = mid - 1
        return -1, comparisons
    
    # ---- tests ----
    data = list(range(0, 2000000, 2))
    print(binary_search(data, 1234566))
    print(binary_search(data, 7))
    print(binary_search([5], 5), binary_search([], 5))
    
    Challenging

    Task 3: First occurrence and insert position

    Write first_index(items, target) that returns the first index of target in a sorted list with duplicates (or −1), in O(log n). Then write insert_position(items, target) that returns where target should be inserted to keep the list sorted (before any equal values). Check it against bisect.bisect_left.

    Starter file (write your code where it says pass # your code here):

    File: b2_4_2_challenging.py
    import bisect
    
    def insert_position(items, target):
        pass  # your code here
    
    def first_index(items, target):
        pass  # your code here
    
    # ---- tests ----
    data = [1, 3, 3, 3, 7, 9, 9]
    print([first_index(data, t) for t in [3, 9, 1, 4]])
    print([insert_position(data, t) for t in [0, 3, 4, 10]])
    import random
    random.seed(1)
    for _ in range(1000):
        lst = sorted(random.randint(0, 20) for _ in range(random.randint(0, 15)))
        t = random.randint(-1, 21)
        assert insert_position(lst, t) == bisect.bisect_left(lst, t)
    print("matches bisect_left")
    

    Expected output when your code is correct:

    [1, 5, 0, -1]
    [0, 1, 4, 7]
    matches bisect_left
    Hint
    When items[mid] equals target, keep searching to the left (high = mid) instead of stopping.
    Model solution
    File: b2_4_2_challenging_solution.py
    import bisect
    
    def insert_position(items, target):
        low, high = 0, len(items)
        while low < high:
            mid = (low + high) // 2
            if items[mid] < target:
                low = mid + 1
            else:
                high = mid
        return low
    
    def first_index(items, target):
        i = insert_position(items, target)
        return i if i < len(items) and items[i] == target else -1
    
    # ---- tests ----
    data = [1, 3, 3, 3, 7, 9, 9]
    print([first_index(data, t) for t in [3, 9, 1, 4]])
    print([insert_position(data, t) for t in [0, 3, 4, 10]])
    import random
    random.seed(1)
    for _ in range(1000):
        lst = sorted(random.randint(0, 20) for _ in range(random.randint(0, 15)))
        t = random.randint(-1, 21)
        assert insert_position(lst, t) == bisect.bisect_left(lst, t)
    print("matches bisect_left")
    

    Learning objectives

    By the end of this page you should be able to:

    1. Construct and trace a linear search that returns the position of the target, or -1 if it is absent.
    2. Construct and trace an iterative binary search, tracking low, high and mid in a trace table.
    3. Explain why binary search needs sorted data, and compare the efficiency of the two searches: O(n) and O(log n) in the worst case.
    4. Calculate the maximum number of comparisons each search needs for a list of n items.
    5. Choose a search technique to meet efficiency requirements, such as searching a directory by name versus by phone number.

    Linear search

    def linear_search(items, target):
        for i in range(len(items)):
            if items[i] == target:
                return i          # found: stop at once
        return -1                 # checked everything: not there

    Check each item in turn from the start. Works on any list, sorted or not, and on structures without index access, such as linked lists. Best case 1 comparison (target first), worst case n (target last or absent): O(n).

    Binary search

    def binary_search(items, target):      # items MUST be sorted
        low = 0
        high = len(items) - 1
        while low <= high:                   # something left to search
            mid = (low + high) // 2
            if items[mid] == target:
                return mid
            elif items[mid] < target:
                low = mid + 1                # target is in the upper half
            else:
                high = mid - 1               # target is in the lower half
        return -1                            # low passed high: not there

    Each comparison halves the part still to be searched, so the worst case is about log₂ n comparisons (exactly ⌊log₂ n⌋ + 1): O(log n). It only works on sorted data with direct access by index. In Java the same algorithm uses int mid = (low + high) / 2; with integer division.

    Comparison

    Linear searchBinary search
    Data must be sorted?NoYes
    Best case1 comparison, O(1)1 comparison, O(1) (target in the middle)
    Worst casen, O(n)⌊log₂ n⌋ + 1, O(log n)
    n = 1,000,000up to 1,000,000up to 20
    SuitsSmall or unsorted lists, data searched rarely, linked lists, searching by a field the data is not sorted onLarge sorted lists searched often

    Choosing a technique: the phone directory

    • A directory sorted by name: finding a number from a name can use binary search, O(log n).
    • Finding the name for a number: the list is not ordered by number, so only linear search works, O(n).
    • If reverse lookups are frequent, it can be worth building a second copy or index sorted by number: a one-off sort, O(n log n), then each lookup is O(log n). If they are rare, linear search is simpler and cheaper overall.

    Use the 中文 button at the top to show or hide the Chinese terms.

    Term中文Meaning

    Choose an answer. You get instant feedback.

    Score: 0 /

    Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

    1. A binary search for 42 is carried out on [3, 8, 12, 19, 23, 31, 37, 42, 50, 58, 64]. Construct a trace table showing low, high and mid for each pass. [4]

    Pass 1: low 0, high 10, mid 5, items[5] = 31 < 42 so low = 6 [1]. Pass 2: low 6, high 10, mid 8, items[8] = 50 > 42 so high = 7 [1]. Pass 3: low 6, high 7, mid 6, items[6] = 37 < 42 so low = 7 [1]. Pass 4: low 7, high 7, mid 7, items[7] = 42: found at index 7 [1].

    2. Construct a Python function linear_search(items, target) that returns the index of target, or -1 if it is not present. [3]

    Loop through every index of items [1]; compare items[i] with target and return i when equal [1]; return -1 after the loop has finished [1].

    3. A sorted list holds 1,000 titles. State the maximum number of comparisons for (a) a linear search, (b) a binary search. [2]

    (a) 1,000 [1]; (b) 10, since 2¹⁰ = 1024 > 1000 [1].

    4. Explain why a binary search cannot be used on an unsorted list. [2]

    Binary search compares the target with the middle item and discards one half on the assumption that all items in it are smaller / larger [1]; in an unsorted list the target could be in the discarded half, so it may report "not found" incorrectly [1].

    5. A school directory of 5,000 entries is stored sorted by surname. Discuss the most efficient way to (a) find a student's phone number from their name, (b) identify the student who owns a given phone number. [4]

    (a) The data is sorted by name, so binary search can be used [1], needing at most about 13 comparisons [1]. (b) The data is not sorted by number, so a linear search is required, up to 5,000 comparisons [1]; if such lookups are frequent, maintaining a second index sorted by number would allow binary search, at the cost of extra memory and of sorting/updating it [1].

    6. Compare linear search and binary search. [4]

    Both locate a target and return its position, and both have a best case of one comparison [1]. Linear search works on unsorted data / any sequential structure, binary search needs sorted data with direct access [1]. Linear search's worst case is O(n), binary search's O(log n) [1]; so binary search is far more efficient for large lists, while linear search may be preferred for small or unsorted lists, or when sorting would cost more than it saves [1].