Lesson 71: Binary search
Halve it again and again
- A linear search checks the items one by one from the start (lesson 48).
- A binary search works only on sorted data. It looks at the middle item and throws away the half that cannot hold the target. Then it repeats with the half that is left.
lowandhighmark the part that is left;mid = (low + high) / 2is its middle.
Find 47
| Look | low–high | mid | ids[mid] | Next |
|---|---|---|---|---|
| 1 | 0–14 | 7 | 34 | low = 8 |
| 2 | 8–14 | 11 | 58 | high = 10 |
| 3 | 8–10 | 9 | 47 | found |
- 34 is too small, so the target is to the right; 58 is too big, so it is to the left.
In the exam
- 9618/32/M/J/24 Q8(b): compare linear and binary search. Mark scheme points: a linear search checks each element in turn until it finds the item or reaches the end; a binary search finds the middle, decides which half holds the item and discards the other half; a binary search needs the data to be sorted, a linear search does not; a binary search usually needs far fewer comparisons.
- 9618/31/M/J/24 Q10(a): a condition for a binary search: the array must be sorted (in ascending or descending order).
רמת קושי 4/5 · 280 מטבעות + בונוס קטן בהשלמה הראשונה היום
The 15 card IDs in ids are sorted. A binary search looks at the middle item first, then throws away the half that cannot hold the number. Type an ID in the Serial Monitor. Right now the program always looks in the left half: fix it. If the middle item is the target, set found = mid; if it is smaller, look in the right half; if it is bigger, look in the left half.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
How much faster is it? binaryLooks counts the looks of a binary search. Write linearLooks: check the items one by one from index 0, count each look, and return the count when you find the target, or after all 15 if it is not there.
לחץ על הרץ כדי לראות את התוצא כאן.