Lesson 4 of 7LO 2.8
Binary search
Binary search finds a value in a sorted list. It checks the middle item and throws away the half that cannot hold the target. Every check halves what is left, so a list of 1,000 items needs at most 10 checks. Linear search might need all 1,000.
- Pass 1low 0, high 6, mid 3. 19 is less than 27, so drop the left half: low = 4.
- Pass 2low 4, high 6, mid 5. 31 is more than 27, so drop the right half: high = 4.
- Pass 3low 4, high 4, mid 4. 27 found at index 4.
The list must be sorted first. If it is not, throwing away half of it could throw away the target.
def binary_search(items, target):
low = 0
high = 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