CAP7004 · Unit 3: Searching and sorting
Linear and binary search
8 practice questions
Key points
- Linear: O(n), no ordering needed
- Binary: O(log n), requires sorted data
- Worst case comparisons = floor(log2 n) + 1
- bisect_left gives the leftmost insertion point
Linear search checks items one by one. Works on unsorted data. Best case O(1) (first item), worst and average O(n).
Binary search needs a sorted sequence. Compare the target with the middle item and discard half:
def bsearch(a, t):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == t: return mid
if a[mid] < t: lo = mid + 1
else: hi = mid - 1
return -1
Time O(log n); iterative version uses O(1) space, recursive O(log n). The worst case takes floor(log2 n) + 1 comparisons: 11 for n = 1024 and 4 for n = 15.
Trace: in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], searching 23 probes index 4 (16), index 7 (56), then index 5 (23): 3 probes. Searching 91 takes 4 probes.
Python: x in list is linear; the bisect module (bisect_left, bisect_right) does binary search on sorted lists. bisect_left returns the leftmost insertion point.
Exam pitfall: binary search on an unsorted list gives wrong answers; sorting first costs O(n log n), so it pays off only for many searches.
Try two questions
Binary search compares the target with one middle element per step. On 1024 sorted items, the most comparisons it can need is:
- 1024
- 9
- 10
- 11
Show the answer
D. floor(log2 1024) + 1 = 11, confirmed by searching for every present and absent target.
You must answer 5 membership queries on 1,000,000 unsorted numbers once. Which is cheapest overall?
- Five linear searches
- Build a balanced tree, then search
- Sort twice for safety
- Sort first, then five binary searches
Show the answer
A. Sorting costs O(n log n), more than five O(n) scans, so sorting does not pay off here.