B2.4.2 Linear and binary search
SL + HLCommand terms: Construct, Trace1. 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.
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.
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?
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.
Is a second copy sorted by number worth it?
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.
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.
8. 45-second speed round: mid and maximum comparisons
Expected output
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
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.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
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):
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
Model solution
It must check every item to find all matches, so it always makes n comparisons: O(n), with no early exit.
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"))
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):
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
Model solution
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))
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):
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
Model solution
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:
- Construct and trace a linear search that returns the position of the target, or -1 if it is absent.
- Construct and trace an iterative binary search, tracking low, high and mid in a trace table.
- 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.
- Calculate the maximum number of comparisons each search needs for a list of n items.
- 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 search | Binary search | |
|---|---|---|
| Data must be sorted? | No | Yes |
| Best case | 1 comparison, O(1) | 1 comparison, O(1) (target in the middle) |
| Worst case | n, O(n) | ⌊log₂ n⌋ + 1, O(log n) |
| n = 1,000,000 | up to 1,000,000 | up to 20 |
| Suits | Small or unsorted lists, data searched rarely, linked lists, searching by a field the data is not sorted on | Large 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]
2. Construct a Python function linear_search(items, target) that returns the index of target, or -1 if it is not present. [3]
3. A sorted list holds 1,000 titles. State the maximum number of comparisons for (a) a linear search, (b) a binary search. [2]
4. Explain why a binary search cannot be used on an unsorted list. [2]
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]
6. Compare linear search and binary search. [4]