- Describe how linear search works
- Write a linear search in Python
- Compare best-case and worst-case searches
You can use lists, loops and if statements. A search algorithm combines all three.
Checking each item
Linear search looks through a list from the start. It compares each item with the target. If it finds a match, it stops. If it reaches the end without a match, the target is not in the list. The list does not need to be sorted, so linear search works on any data.
A search that checks each item in order until it finds the target or reaches the end.
The value that a search algorithm is looking for.
Efficiency
In the best case, the target is first and only 1 comparison is needed. In the worst case, the target is last or missing, so all n items are checked. On average, a search through a list checks about half of the items when the target is present.
Write a function that returns the position of a target, or −1 if it is missing.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1Searching [4, 9, 2] for 2 checks 4, then 9, then 2, and returns position 2.
Put return -1 after the loop. Inside the loop, it would stop after checking the first item.
Practice
Quick check
Where does linear search begin?
What is the worst case for a list of n items?
When should a linear search stop early?
- Linear search checks items in order.
- It stops when it finds the target.
- It works on unsorted lists.
- The worst case checks all n items.
