Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course
2.4 Binary Search: Algorithm, Tracing and Applications
Unit 2 – Computational Thinking and Algorithms · 80 min read · 9 MCQs to check yourself
Linear vs binary search explained with visuals and Python code
1. The idea – halve the search space
Binary search finds a target in a sorted list by comparing it with the middle element:
- equal → found;
- target smaller → search only the left half;
- target larger → search only the right half.
Each comparison throws away half of the remaining items, so the search space shrinks 1,000,000 → 500,000 → 250,000 → … → 1 in about 20 steps.
2. Algorithm
- Set
low = 0,high = n − 1. - While
low ≤ high:mid = (low + high) // 2- if
list[mid] == target→ returnmid - if
list[mid] < target→low = mid + 1 - else →
high = mid − 1
- Return −1 (not found).
def binary_search(items, target):
low, high = 0, len(items) - 1
steps = 0
while low <= high:
mid = (low + high) // 2
steps += 1
print(f"step {steps}: low={low} high={high} mid={mid} value={items[mid]}")
if items[mid] == target:
return mid
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
data = [3, 8, 12, 17, 23, 31, 38, 45, 52, 60, 71]
print("index:", binary_search(data, 52))
print("index:", binary_search(data, 20))
Output:
step 1: low=0 high=10 mid=5 value=31
step 2: low=6 high=10 mid=8 value=52
index: 8
step 1: low=0 high=10 mid=5 value=31
step 2: low=0 high=4 mid=2 value=12
step 3: low=3 high=4 mid=3 value=17
step 4: low=4 high=4 mid=4 value=23
index: -1
3. Binary vs linear search
| Linear search | Binary search | |
|---|---|---|
| Data must be sorted? | No | Yes |
| Method | Check items one by one | Check the middle, discard half |
| Worst-case comparisons (n = 1,000,000) | 1,000,000 | 20 |
| Time complexity | O(n) | O(log n) |
| Best for | Small or unsorted lists, linked lists | Large sorted arrays, many searches |
Maximum comparisons = ⌊log₂ n⌋ + 1. For n = 1,000: 10; n = 1,000,000: 20; n = 1,000,000,000: 30.
The main advantage of binary search is that it reduces the search space by half at each step. Its limitation is that data must be sorted (and kept sorted), and it needs direct (index) access.
4. Applications of binary search
- Searching a word in a dictionary or a name in a sorted contact list.
- Database indexes and search engines (keywords stored in sorted order).
- Finding a roll number in a sorted result list of a board.
- Debugging with “git bisect” – find which version introduced a bug by halving the list of versions.
- Finding a value in a range: e.g. the smallest price that fits a budget, or the square root of a number by guessing.
- Auto-complete in a sorted list of words.
Short and long questions
1. Trace the binary search algorithm to find 60 in the list [5, 12, 18, 25, 33, 41, 47, 52, 60, 68, 75]. Show low, high and mid in a table, give the number of comparisons, and compare it with linear search for the same list. (4 + 2)
Model answer
Trace (4): n = 11, indices 0–10.
| Step | low | high | mid | items[mid] | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 10 | 5 | 41 | 41 < 60 | low = 6 |
| 2 | 6 | 10 | 8 | 60 | 60 = 60 | found at index 8 |
| Comparisons: 2. |
Comparison with linear search (2): linear search checks 5, 12, 18, 25, 33, 41, 47, 52, 60 → 9 comparisons. Binary search needed only 2 because each step discards half the list. For 11 items the worst case is 4 comparisons for binary search vs 11 for linear. Binary search requires the list to be sorted; linear does not.
2. Compare linear search and binary search (any three points).
Model answer
| Linear search | Binary search |
|---|---|
| Works on sorted or unsorted data | Needs sorted data |
| Checks items one by one – O(n) | Halves the range each step – O(log n) |
| Simple; good for small lists | Much faster for large lists searched often |
3. Write a Python function for binary search that returns the index of the target or −1.
Model answer
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
4. Trace binary search for 23 in [4, 9, 15, 23, 30, 42, 57] showing low, high and mid at each step.
Model answer
| Step | low | high | mid | items[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 23 | equal → found at index 3 |
| Only one comparison is needed because 23 is exactly the middle element. |
5. A search engine needs to quickly find a keyword from a sorted list of millions of words. Which algorithm would be most efficient, and how does it work? (1 + 2)
Model answer
Binary search (1). It compares the keyword with the middle word; if equal, it is found; if the keyword comes before it alphabetically, it searches only the left half, otherwise the right half. It repeats until found or the range is empty – about log₂(n) ≈ 20–25 comparisons for millions of words (2).
6. How is the binary search algorithm useful in searching large datasets efficiently? Give any three key points.
Model answer
- It halves the search space with every comparison, so even 1,000,000 items need only about 20 comparisons (O(log n)) instead of up to 1,000,000 (O(n)).
- It is ideal when data is sorted and searched many times – e.g. database indexes, dictionaries, sorted result lists.
- Its speed grows very slowly with data size – doubling the data adds only one more comparison.
This lesson ends with a quiz of 9 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 2.3 Trees: Binary Trees, BST, Traversals, DFS and BFS · Next: Unit 2 Review, Situational Quiz and Unit Test
All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course