Linear Search vs Binary Search. Tracing and Efficiency.
(a) List must be SORTED (ordered).
(b) Linear Search checks every item sequentially, so order doesn't matter.
| Statement | Linear | Binary |
|---|---|---|
| Checks every item one by one. | ||
| Calculates a midpoint to divide the list. | ||
| Significantly faster for large, sorted lists. |
(a) 7 checks.
(b) Checks every item (Ali to Zoe), finds no match, reports "Not Found".
Mid = (Low + High) / 2 (Round down).
Step 2: New Range [5-8]. Midpoint?
Step 3: New Range? Midpoint?
Step 2: Range [5-8]. Mid = (5+8)/2 = 6. Value 22.
22 > 19, Discard Right.
Step 3: Range [5-5]. Mid = (5+5)/2 = 5. Value 19.
Found!
| Stage | Low | High | Mid | Value |
|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 15 |
| 2 | ||||
| 3 |
Stage 2: Low: 0, High: 3, Mid: 1, Value: 5
Stage 3: Low: 0, High: 0, Mid: 0, Value: 2 (Found)
The list is NOT sorted. Binary Search works by discarding half the list based on order logic. Without order, it might discard the half containing the item.
1. target (or item)
2. True
3. index
4. "Not Found"
Linear: Worst case checks 1,000,000 items (Very Slow).
Binary: Worst case checks approx 20 items (Log2 n) (Extremely Fast).
If the target is at the start of the list (Best Case). Linear finds it in 1 check. Binary might take a few divisions.