Binary search in Python, visualized step by step
PythonC
To find a value in a sorted array, look at the middle one: if it is smaller than the target, search the right half; if bigger, the left half. Every look rules out half of what is left.
binary_search.py
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72]
target = 23
lo, hi = 0, len(nums) - 1
found = -1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
found = mid
break
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
print(found)
How Binary search works
- lo and hi mark the two ends of the range that may still hold the answer.
- Look at the middle, mid: if it is the target, done.
- mid smaller than the target: the answer is to the right, lo = mid + 1; bigger: hi = mid − 1.
- When lo passes hi, the value is not there.
What to watch
lo and hiThe distance between them roughly halves every step.
midWith 9 values it takes at most 4 looks to know the answer.
FAQ
What is the time complexity of binary search?
O(log n): each step halves the range, so a million values take at most 20 looks.
What does binary search need?
A sorted array that can be indexed directly (a linked list will not do).
Why write mid as lo + (hi − lo) / 2?
In C, lo + hi can overflow an int; this form cannot. Python integers have no limit, so (lo + hi) // 2 is fine there.