Lesson 71: Binary search
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
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.
English
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.
English
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.
点击“运行”查看此处输出。