A sorted list lets you find any value without scanning it end to end. Binary search keeps a window [lo, hi] of candidate indices, looks at the middle element, and throws away the half that cannot contain the target. Each step halves the window, so a list of a million items is searched in about twenty comparisons.
Implement search(arr, target):
This is the foundation every later step builds on, so make the boundaries exact.
def search(arr, target):
"""Return the index of target in sorted arr, or -1 if absent."""
# TODO: binary search. Track lo and hi, compare arr[mid] to target.
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
A sorted list lets you find any value without scanning it end to end. Binary search keeps a window [lo, hi] of candidate indices, looks at the middle element, and throws away the half that cannot contain the target. Each step halves the window, so a list of a million items is searched in about twenty comparisons.
Implement search(arr, target):
This is the foundation every later step builds on, so make the boundaries exact.
Press Run Tests or ββ© to check your solution.