Imagine you have a stack of exam papers and you need to find a specific student's work. You look at each paper, one by one. That's linear search.
Linear search checks every element in a list, one at a time, until it finds the target or reaches the end.
Algorithm:
For each item in the list:
If the item equals the target:
Return the item's position
If we reach the end:
Return -1 (not found)
Key facts:
find_name(names, target) using linear search. Return index or -1.def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
Looking up a word in a dictionary? You open it in the middle, check if your word comes before or after, and discard half the pages. That's binary search!
Binary search repeatedly divides the search interval in half. Only works on sorted data!
Algorithm:
1. Set left = 0, right = len-1
2. While left ≤ right:
a. mid = (left + right) // 2
b. If items[mid] == target → Found! Return mid
c. If items[mid] < target → left = mid + 1
d. If items[mid] > target → right = mid - 1
3. Not found → Return -1
| Criteria | Linear | Binary |
|---|---|---|
| Data requirement | Any list | Sorted only |
| Worst case | O(n) | O(log n) |
| Best for | Small/unsorted | Large sorted lists |