A binary search is an efficient searching algorithm that works by repeatedly halving the search space. It compares the target to the middle element of a sorted list, then eliminates the half that cannot contain the target.
Critical requirement: The list must be sorted before binary search can be applied. This is its key limitation compared to linear search.
Calculate the middle index: mid = (low + high) ÷ 2 (integer division). Compare list[mid] with the target.
If list[mid] == target → found! Return mid.
If list[mid] < target → target must be in the right half. Set low = mid + 1.
If list[mid] > target → target must be in the left half. Set high = mid - 1.
Repeat with the new search range (low to high) until the target is found, or low > high (target not in list).
Sorted list: [2, 5, 8, 12, 16, 23, 38, 45, 56, 72] — Search for 23
| Pass | low | high | mid | list[mid] | Compare to 23 | Result |
|---|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 16 | 16 < 23 | low = mid+1 = 5 |
| 2 | 5 | 9 | 7 | 45 | 45 > 23 | high = mid-1 = 6 |
| 3 | 5 | 6 | 5 | 23 | 23 == 23 | Found at index 5 |
Only 3 comparisons needed for a 10-item list — compare with up to 10 for linear search.
Binary search is O(log₂n) — with each comparison, the search space is halved. For a sorted list of 1024 items, binary search needs at most 10 comparisons (log₂1024 = 10), while linear search could need 1024.
| List size (n) | Binary: max comparisons (log₂n) | Linear: max comparisons |
|---|---|---|
| 8 | 3 | 8 |
| 64 | 6 | 64 |
| 1,024 | 10 | 1,024 |
| 1,048,576 | 20 | 1,048,576 |
| Advantages | Disadvantages |
|---|---|
| Much faster than linear search for large lists — O(log n) | Requires the list to be sorted first |
| Efficient — eliminates half the remaining items each pass | Sorting adds overhead if data is not already sorted |
| Suitable for large datasets | More complex to implement than linear search |
| Predictable maximum comparisons | Not suitable for data that changes frequently |
| Feature | Linear Search | Binary Search |
|---|---|---|
| Sorted list required? | No | Yes |
| Time complexity (worst) | O(n) | O(log n) |
| Best for | Small / unsorted lists | Large sorted lists |
| How it searches | One by one from start | Halves search space each time |
| Not found return | -1 | -1 |
| Implementation | Simpler | More complex |
8 questions · 20 marks
| Term | Definition |
|---|
10 questions · 10 marks · 10 minutes