Searching and sorting
Find things in data quickly: linear search, binary search on sorted data, a simple sorting algorithm traced by hand, and why sorting first often pays off.
Lesson 2 of 6 · 35 min · Self-paced · Free
Why searching and sorting matter
A robot that combines two sensors constantly asks questions like "which camera frame was taken closest to this force reading?" A log of a long test may hold millions of timestamped rows. Finding the right one by checking every row is slow; finding it in twenty steps is possible — if the data is sorted. Searching and sorting are some of the most studied algorithms in computing, and they show beautifully how the right method changes the cost from O(n) to O(log n).
Linear search
The simplest search looks at each item in turn until it finds a match:
def linear_search(items, target):
"""Return (index of target, steps taken), or (-1, steps) if absent."""
steps = 0
for i, x in enumerate(items):
steps += 1
if x == target:
return i, steps
return -1, steps
parts = ["M3-bolt", "bearing-608", "spacer-10", "M3-nut", "servo-horn"]
print(linear_search(parts, "M3-nut"))
print(linear_search(parts, "gear-20T"))Output:
(3, 4)
(-1, 5)Linear search works on any list, sorted or not, and is perfectly fine for small lists. But its worst case — the target is last or absent — checks every item, so it is O(n). A million items means up to a million comparisons.
Binary search
If the list is sorted, there is a much better way. Think of finding a word in a dictionary: you open it in the middle, see whether your word comes before or after that page, and throw away half the book. Repeat with the remaining half, and so on.
def binary_search(items, target):
"""items must be sorted in increasing order."""
low, high = 0, len(items) - 1
steps = 0
while low <= high:
steps += 1
mid = (low + high) // 2
if items[mid] == target:
return mid, steps
elif items[mid] < target:
low = mid + 1 # target is in the upper half
else:
high = mid - 1 # target is in the lower half
return -1, steps
print(binary_search([3, 8, 12, 15, 21, 30, 42], 21))Output:
(4, 3)Trace it by hand. The search range starts as indices 0 to 6. Step 1: the middle is index 3, value 15, which is less than 21, so the target must be in indices 4 to 6. Step 2: the middle is index 5, value 30, too big, so the range becomes index 4 alone. Step 3: index 4 holds 21. Found.
Each step halves the range, so a list of n items needs at most about log₂ n + 1 steps: O(log n). On a large log the difference is dramatic. Here is a made-up log with a timestamp every 10 milliseconds — a million entries:
def linear_search(items, target):
steps = 0
for i, x in enumerate(items):
steps += 1
if x == target:
return i, steps
return -1, steps
def binary_search(items, target):
low, high = 0, len(items) - 1
steps = 0
while low <= high:
steps += 1
mid = (low + high) // 2
if items[mid] == target:
return mid, steps
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1, steps
timestamps_ms = list(range(0, 10_000_000, 10)) # 1,000,000 sorted entries
print(len(timestamps_ms))
print(linear_search(timestamps_ms, 9_876_540))
print(binary_search(timestamps_ms, 9_876_540))Output:
1000000
(987654, 987655)
(987654, 20)Nearly a million steps against 20. Binary search is easy to get slightly wrong, though: a < where you need <=, or high = mid instead of mid - 1, can make it miss items or loop forever. Test it on small lists, including an empty list, a one-item list and targets at both ends. Python's standard bisect module provides carefully tested versions; bisect.bisect_left(items, target) returns the position where target is, or would be inserted, which is exactly what you need to find the nearest timestamp rather than an exact match.
Sorting: insertion sort
Binary search needs sorted data, so how do you sort? Insertion sort is the method many people use for a hand of playing cards: take each new card and slide it left past every larger card until it is in place.
def insertion_sort(values):
items = values.copy() # leave the original alone
for i in range(1, len(items)):
current = items[i]
j = i - 1
while j >= 0 and items[j] > current:
items[j + 1] = items[j] # shift the larger item right
j -= 1
items[j + 1] = current # drop current into the gap
print(f"after placing {current:2d}: {items}")
return items
insertion_sort([42, 17, 8, 30, 23])Output:
after placing 17: [17, 42, 8, 30, 23]
after placing 8: [8, 17, 42, 30, 23]
after placing 30: [8, 17, 30, 42, 23]
after placing 23: [8, 17, 23, 30, 42]After each step, the front part of the list is sorted. In the worst case (a list in reverse order) each new item slides past every item before it, giving about n²/2 moves: O(n²). But if the data is almost sorted — like timestamps that arrive slightly out of order — each item moves only a little, and insertion sort is close to O(n).
Sorting in practice
For real work, use Python's built-in sorted (or the list method .sort()). It uses an algorithm called Timsort, which is O(n log n) in the worst case and very fast on partly sorted data. You can sort records by any field by passing a key function:
parts = [
{"name": "bracket", "mass_g": 42},
{"name": "bolt", "mass_g": 3},
{"name": "wheel", "mass_g": 65},
]
def by_mass(part):
return part["mass_g"]
for p in sorted(parts, key=by_mass, reverse=True):
print(p["name"], p["mass_g"])Output:
wheel 65
bracket 42
bolt 3Why sorted data helps
Sorting once makes many later questions cheap:
- Searching: binary search in O(log n).
- Minimum and maximum: the first and last items.
- Median: the middle item, a robust "typical value" that a single outlier cannot drag around.
- Duplicates: equal values end up next to each other.
Is it worth it? Sorting costs O(n log n). If you search only once, a single O(n) linear search is cheaper. If you will search many times, sort once and every search afterwards costs only O(log n).
Recap
- Linear search works on any list but is O(n).
- Binary search halves the range each step, O(log n), but needs sorted data and careful boundary handling.
- Insertion sort is simple and O(n²) in the worst case, but fast on nearly sorted data.
- In practice, use
sortedwith akey; it is O(n log n). - Sort once when you will search, rank or take medians many times.
Knowledge check
Check your understanding
Project
Programming project: aligning two sensor logs
Two made-up sensor logs were recorded at different rates: a camera log with a timestamp every 33 ms and a force log with a timestamp every 10 ms, both starting at 0 and lasting 10 seconds. Create them in Python as sorted lists of timestamps in milliseconds.
- For each camera timestamp, find the force timestamp closest to it. Do it first with linear search, then with
bisect.bisect_left(check the item at the returned position and the one before it). - Count the total comparisons made by your linear method, and time both methods with
time.perf_counter(). - Check that both methods give identical matches.
- Write your own
insertion_sortand test it againstsortedon 20 random lists (use therandommodule), including an empty list and a list with repeated values.
No hardware is required.
Deliverables
- A Python 3 program that matches each camera timestamp to the nearest force timestamp in two ways
- Comparison counts and timings for both methods
- Test output showing insertion_sort agrees with sorted
Go further
- Python documentation — bisect: array bisection algorithm ↗
Tested binary-search functions for finding positions in sorted lists.
- Python documentation — Sorting Techniques ↗
How to use sorted and .sort with key functions, reverse order and stable sorting.
- Binary search — Wikipedia ↗
The algorithm, its variants and its many off-by-one pitfalls.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.