
Code
Binary Search
Linear search checks items one by one: up to n steps, O(n).
If the list is sorted, you can do much better. Look at the middle item:
- If it's the target, you're done.
- If the target is bigger, it can only be in the right half.
- If it's smaller, it can only be in the left half.
Each step throws away half the list. A million items take only about 20 steps, because 2²⁰ ≈ 1,000,000. That's O(log n).
lo, hi = 0, len(items) - 1 # the part still worth searching
while lo <= hi:
mid = (lo + hi) // 2
... # move lo or hi past mid
Pip tip: Python's
bisectmodule does binary search for you in real code. Writing it once yourself is the best way to understand it, and it's a classic interview question!
Assignment
Write binary_search(items, target):
itemsis a list sorted from smallest to largest.- Return the index of
target, or-1if it isn't there. - Use the halving strategy. Don't loop over every item (the tests check!).
Write binary_search(items, target):
itemsis a list sorted from smallest to largest.- Return the index of
target, or-1if it isn't there. - Use the halving strategy. Don't loop over every item (the tests check!).
main.py Python sleeping
Press Run to try your code, then Check to test it.