Check the middle, throw away half, repeat. Sixteen items in five checks, a million in twenty — as long as one thing is true about the list. That one thing is half of every exam question about it.
No reading — this page is the reading. Runestone doesn’t cover Unit 4 (search, efficiency, limits, simulation), so everything you need is right here.
Programs, Algorithms region. Yesterday’s linear search worked on anything and paid for it: n checks. Today’s algorithm is dramatically faster — and it only works under one condition, which the exam tests just as often as the algorithm itself.
Someone always starts at 1. Someone always does it in 7 or fewer. The difference between those two people is today’s whole lesson.
Picture a phone book (or a dictionary). Open it to the middle. The name you want is either on this page, before it, or after it — so you can tear the book in half and throw away the wrong half. Repeat. A 1,000-page book is down to one page in about 10 tears.
That’s binary search: check the middle element; if it’s not the target, discard the half the target can’t be in; repeat on what’s left.
def binary_search(items, target): low = 0 high = len(items) - 1 while low <= high: mid = (low + high) // 2 if items[mid] == target: return mid if target < items[mid]: high = mid - 1 # keep left half else: low = mid + 1 # keep right half return -1
PROCEDURE binarySearch(items, target) { low ← 1 high ← LENGTH(items) REPEAT UNTIL (low > high) { mid ← (low + high - ((low + high) MOD 2)) / 2 IF (items[mid] = target) { RETURN (mid) } IF (target < items[mid]) { high ← mid - 1 } ELSE { low ← mid + 1 } } RETURN (-1) }
Hover or tap a line to light its twin. Line 4 is the loop flip again —
while low <= high becomes REPEAT UNTIL low > high. Line 5: AP Pseudocode
has no “round down” division, so subtracting MOD 2 first makes the sum even. You will
never have to write binary search on the exam — you’ll have to reason about it.
Sixteen sorted numbers. Pick a target and press Check middle. Watch the live range (bright) shrink by half each time. Then flip the list to unsorted and watch it fail.
Try every target on the sorted list: you’ll never need more than 5 checks for 16 items. Linear search’s worst case on the same list is 16.
Build binary_search with a counter, run the same tests as Part 1,
fill the binary column of your table, then break it on an unsorted list (Part 4).
Five questions. The first one is nearly free points — if you remember one word.
Binary search is only free if the data is already in order — and keeping data in order is real, ongoing work. Every time a library adds a book, a bank opens an account, or a school enrolls a student, something has to slot the new record into the right place.
Organizations pay that cost up front because they search the same data millions of times. Fast lookup isn’t magic; it’s preparation someone already did.