A sorted list is stored as data = [3, 8, 12, 19, 25, 31, 40, 47] (indices 0 to 7). A binary search looks for the value 31. Count each examination of a middle item as one comparison. The midpoint is calculated as mid = (low + high) // 2, starting with low = 0 and high = 7.
(a) State the value of mid and the item examined in the first comparison. [2]
(b) Show how low and high change, and state how many comparisons are needed to find 31. [2]
- First mid = (0 + 7) // 2 = 3(1)
- Item examined is data[3] = 19(1)
- 19 < 31 so the lower half is discarded: low becomes 4 (high stays 7); second mid = 5 gives data[5] = 31(1)
- Found after 2 comparisons(1)
- Answer: (a) mid = 3, item 19. (b) low = 4, high = 7; 2 comparisons.
- Examiner tip: Show the midpoint calculation; students often forget to move low to mid + 1 and instead set low = mid.