Searching
14 min
Linear search checks every element in order — O(n), but works on any iterable, sorted or not.
Binary search only works on sorted data, but is O(log n): compare the target to the middle element, and eliminate half the remaining range every step. That's the same halving idea behind BSTs from the previous course.
def linear_search(nums, target):
for i, x in enumerate(nums):
if x == target:
return i
return -1
Each iteration halves the search space — 1,000,000 elements take at most ~20 comparisons instead of up to 1,000,000.
Python's bisect module does this for you in production code:
import bisect
nums = [1, 3, 5, 7, 9]
bisect.bisect_left(nums, 5) # 2 — index where 5 is (or would be inserted)
bisect.insort(nums, 6) # inserts 6 keeping the list sorted
Writing binary search by hand is worth doing once for the mental model —
in real code, reach for bisect.
Write a function `linear_search(nums, target)` that returns the index of the first occurrence of `target` in `nums`, or -1 if it isn't present.
Write a function `binary_search(nums, target)`, where `nums` is sorted ascending. Return the index of `target`, or -1 if absent — using binary search, not a linear scan.
Binary search requires the input to be ______ before it can be applied.
You can implement both linear and binary search, and know when each applies.