GCSE · 4 exercises
Python searching
Linear search looks at each item in turn. Binary search works on a sorted list: look at the middle, then throw away the half that can't hold the answer.
Binary search finds an item among a million in about 20 steps.
def find(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Watch for: lo = mid instead of mid + 1 can loop for ever when two items are left.
Exercises
- Binary searchFind a number in a sorted list with binary search: look at the middle and keepAdvanced
- First and last positionA sorted list may contain repeats.Advanced
- Integer square rootFind the largest whole number r with r * r <= n using binary search (no ** 0.5,Advanced
- How many in range?Answer many questions: how many numbers of the list lie between a and b (bothAdvanced