Classic Binary Search Without Bugs
Nail the low, high, and mid loop.
Halve the Search Space
Binary search finds a value in a sorted list by halving the range each step. That turns a slow O(n) scan into a fast O(log n) search.
a = [1, 3, 5, 7, 9] # must be sortedSorted Is the One Rule
Binary search only works on sorted data. If the list is unordered, sort it first or the result is meaningless and wrong.
a.sort() # ascending order requiredAll lessons in this course
- Classic Binary Search Without Bugs
- bisect_left and bisect_right
- First True: Predicate Binary Search
- Binary Search on the Answer