100 XP

28. Binary search

Advanced searching loops

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

Inputnumbers = [1, 3, 5, 7, 9], target = 7
Output3
Explanation7 is at index 3, counting from 0.

Example 2

Inputnumbers = [1, 2, 2, 2, 3], target = 2
Output1
ExplanationThe 2s are at 1, 2 and 3; the first is 1.

Example 3

Inputnumbers = [1, 3, 5, 7, 9], target = 4
Output-1
Explanation4 is not in the list.

Constraints

  • numbers has 0 to 100 whole numbers, sorted from smallest to largest. A number may repeat.
  • target is a whole number.

Submit also runs 13 more tests you can't see.

Practises Functions (lesson 16).

Code
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