28. Binary search
Write a function search(numbers, target) that takes a list of whole numbers sorted from smallest to largest, and a
whole number target. A number may appear more than once. Return the index of the first target in the list (the
leftmost one; indexes count from 0), or -1 if target isn't in the list. An empty list holds nothing, so for it the
answer is -1.
Use binary search, and don't use .index() or in. Binary search looks at the middle item of the part of the list
still to search:
- if it is smaller than the target, the first target can only be after it, so search the half after it;
- if it is bigger than the target, search the half before it;
- if it is the target, remember its index. An earlier copy may still come before it, so keep searching the half before it.
Each step throws away half of what is left. When nothing is left, the answer is the index you remembered last, or the number -1 if the target never came up.
Example 1
numbers = [1, 3, 5, 7, 9], target = 73Example 2
numbers = [1, 2, 2, 2, 3], target = 21Example 3
numbers = [1, 3, 5, 7, 9], target = 4-1Constraints
numbershas 0 to 100 whole numbers, sorted from smallest to largest. A number may repeat.targetis a whole number.
Submit also runs 13 more tests you can't see.
Practises Functions (lesson 16).
- Keep two indexes,
low = 0andhigh = len(numbers) - 1, andfound = -1for the answer so far. Whilelow <= high, look at the middle item,mid = (low + high) // 2. - If
numbers[mid]is too small, the first target can only be after it:low = mid + 1. If it is too big:high = mid - 1. - If it is the target, don't return yet: an earlier copy may come before it. Set
found = midand keep searching the left part withhigh = mid - 1. Whenlowpasseshigh, returnfound; an empty list never enters the loop and gives -1.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def search(numbers, target):
"""Find the first index of target in a sorted list.
numbers: list of int, sorted smallest first; a number
may appear more than once
target: int, the number to look for
Returns: int, the index of the first target, or -1 if
it isn't in the list
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.