01 / 20

Binary
Search

Master the divide-and-conquer strategy that finds any element in a sorted list in \( O(\log n) \) time: exponentially faster than checking every item.

AP Computer Science Principles

What Is Searching?

Searching means locating a specific value (called the target) inside a collection of data. Think of looking up a word in a dictionary or finding a contact on your phone.

Linear Search
Check every element one by one from start to end. Works on any list.
Binary Search
Repeatedly cut the list in half. Requires the list to be sorted first.

The Phone Book Analogy

Imagine looking for "Martinez" in a phone book with 1,000 pages. You wouldn't start at page 1 and flip one page at a time. Instead you:

1
Open to the middle (page 500). "M" is around here: close!
2
Compare: The page shows "L" names. "M" comes after "L," so look in the right half.
3
Repeat: Open the middle of pages 501-1000, compare, and halve again.

Why Sorted Order Matters

Unsorted 42 17 5 91 33 ✕ Can't halve Sorted 5 17 33 42 91 ✓ Binary search ready

Binary search can only work on sorted data. When the middle value is too large, everything to its right is also too large: we can safely ignore that half. This guarantee breaks if the data is unsorted.

The Binary Search Algorithm

1
Set boundaries: \(\text{low} = 0\), \(\text{high} = n - 1\).
2
Find the midpoint: \(\text{mid} = \lfloor (\text{low} + \text{high}) / 2 \rfloor\).
3
Compare: If \(\text{list}[\text{mid}] = \text{target}\), done.
4
If \(\text{target} < \text{list}[\text{mid}]\), set \(\text{high} = \text{mid} - 1\) (search left half).
5
If \(\text{target} > \text{list}[\text{mid}]\), set \(\text{low} = \text{mid} + 1\) (search right half).
6
Repeat steps 2-5 while \(\text{low} \leq \text{high}\). If loop ends, target is not found.

Efficiency: \( O(\log_2 n) \)

Number of elements (n) Steps 0 200 400 600 800 1000 O(n) O(log n) Linear Search Binary Search

Linear vs Binary Search

Linear Search Binary Search
Requires sorted data? No Yes
Best case \( O(1) \) \( O(1) \)
Worst case \( O(n) \) \( O(\log n) \)
1,000 elements (worst) 1,000 steps 10 steps
Implementation Simple loop Slightly more complex
When to use Small or unsorted data Large, sorted data

Binary Search in Pseudocode

PROCEDURE binarySearch(list, target) { low ← 0 high ← LENGTH(list) - 1 REPEAT UNTIL low > high { mid ← FLOOR((low + high) / 2) IF list[mid] = target RETURN mid // Found it! ELSE IF target < list[mid] high ← mid - 1 // Search left half ELSE low ← mid + 1 // Search right half } RETURN -1 // Not found }

How to Apply Binary Search

1
Verify the list is sorted. If not, sort it first (or use linear search).
2
Identify your target value and the list boundaries: \(\text{low} = 0\), \(\text{high} = n - 1\).
3
Compute mid. Use \(\lfloor (\text{low} + \text{high}) / 2 \rfloor\). Compare the middle element to the target.
4
Eliminate half. If target is smaller, discard the right half. If larger, discard the left half.
5
Repeat until found or \(\text{low} > \text{high}\) (not found).

Example 1: Find 23

Step 1 Step 2 Step 3 3 7 11 15 mid 23 28 35 42 23 > 15 → right 3 7 11 15 23 28 mid 35 42 23 < 28 → left 23 FOUND ✓ 3 steps! idx 0 idx 1 idx 2 idx 3 idx 4 idx 5 idx 6 idx 7

A sorted collection makes discarded search ranges meaningful

An archivist opens a specimen drawer beside unordered return trays.Sorted order makes it possible to discard an entire search range after one comparison. An unsorted collection does not support the same elimination.

Binary search with AP-style list indices

Three search ranges use positions 1 through 9 and narrow to target 23 at position 6.This example uses AP-style list positions 1 through 9. Searching for 23 tests the midpoint values 17, 31 and 23 and returns position 6. The list is sorted before searching.

Count comparisons as the list grows

A step graph plots the exact worst-case binary-search probe count against list size on a log₂ horizontal axis.For inclusive midpoint binary search on n ≥ 1 items, the maximum number of probes is floor(log₂ n) + 1. The horizontal axis uses a log₂ scale; the count measures search probes after sorting.

Example 2: Find 50 (Not Found)

List: [2, 8, 14, 27, 33, 41, 56, 72]. Target: 50.

1
low=0, high=7, mid=3. list[3] = 27. Since \(50 > 27\), set low = 4.
2
low=4, high=7, mid=5. list[5] = 41. Since \(50 > 41\), set low = 6.
3
low=6, high=7, mid=6. list[6] = 56. Since \(50 < 56\), set high = 5.
4
low=6, high=5. Since \(\text{low} > \text{high}\), 50 is not in the list. Return \(-1\).

Example 3: 1 Million Items

Suppose you have a sorted database of 1,000,000 records and you need to find one specific record.

Linear Search
Worst case: 1,000,000 comparisons. If each takes 1 microsecond, that's 1 full second.
Binary Search
Worst case: \( \lceil \log_2 1{,}000{,}000 \rceil = \) 20 comparisons. That's 20 microseconds.

The Halving Pattern

16 elements 8 elements 8 eliminated 4 eliminated 4 2 1 Step 1 Step 2 Step 3 Step 4 Found!

Common Mistakes

✕ Using on Unsorted Data
Binary search requires sorted data. Applying it to an unsorted list will produce wrong results: the halving logic assumes order.
✕ Off-by-One Errors
Setting \(\text{high} = n\) instead of \(n - 1\), or using \(\text{mid} - 1\) / \(\text{mid} + 1\) incorrectly, can skip elements or loop forever.
✕ Confusing Steps with Comparisons
The max steps is \(\lceil \log_2 n \rceil\), not \(\log_2 n\) exactly. Always round up to the next whole number.

Binary Search Summary

Property Detail
Precondition Data must be sorted
Strategy Divide and conquer: halve repeatedly
Best case \( O(1) \) : target is at mid on first check
Worst case \( O(\log_2 n) \)
Max steps for \( n = 1024 \) 10
Max steps for \( n = 1{,}000{,}000 \) 20
When NOT to use Unsorted data, very small lists

Question 1 of 5

A sorted list has 512 elements. What is the maximum number of comparisons binary search needs to find a target (or determine it's not present)?

Question 2 of 5

Which of the following is a necessary precondition for binary search to work correctly?

Question 3 of 5

You binary search the sorted list [1, 4, 9, 16, 25, 36, 49] for the value 36. Which element is checked first?

Question 4 of 5

A sorted list has 2,000 elements. Approximately how many times faster is binary search than linear search in the worst case?

Question 5 of 5

During binary search, if the target is less than the middle element, what happens next?