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.
출력을 보려면 '실행'을 클릭하세요.