12.1 What it is and When to Use it
Think about how you find a name in an unsorted class register. You start at the top and read down the list one name at a time until you reach the one you want — or until you run out of names. You do not need the list to be in any special order; you simply check every entry in turn. That everyday habit is a linear search.
A linear search does three simple things, over and over:
- 1. Look at the current element.
- 2. Is it the target? If yes — stop, success.
- 3. If no — move to the next element. Repeat until you find it or run off the end.
- Use a linear search when the data is unsorted, the list is small, or simplicity matters more than speed.
- If the data is already sorted and large, a binary search is much faster.
What is a Linear Search?
12.1B Interactive Simulator
Try the linear search yourself. Change the array and target values, then click Start. Use Step to move one line at a time, or Play to auto-run. Watch the code highlight on the right while the simulation updates on the left.
Simulation
Status: Click Start to begin the simulation.
Code
1found = False2for i in range(len(data)):3 if data[i] == target:4 found = True5 break6if found:7 print("Found")8else:9 print("Not found")12.2 Using a FOR Loop and a Flag
The plan in plain English: set a flag found to False; loop through every element; if an element matches the target, set found = True and stop early with break. After the loop, the flag tells you what happened.
marks = [42, 17, 88, 53, 9, 61]
target = 53
found = False
for value in marks:
if value == target:
found = True
break # stop early — no need to keep looking
if found:
print("Value found")
else:
print("Value not found")- A search is only complete when your program does something for both "found" and "not found".
- After the loop, check the flag and output the appropriate message.
- Loop over every element in data
- Compare each to target
- Return True on a match (exits the function early)
- Return False after the loop (not found)
- Same pattern: header, loop, compare, return early on match
- Return False after the loop
- Index 0: 4 is not 9 (1 comparison)
- Index 1: 8 is not 9 (2 comparisons)
- Index 2: 9 = 9 — stop (3 comparisons)
- A linear search stops at the first match
- Check each index from 0
- The duplicate 5 at index 3 is never reached
- 8 is not in the list
- The flag never changes from False
- Does the flag ever switch to True?
- 6 is at index 1
FOR Loop and Flag
12.3 Returning the Position (or -1)
The trick is to return the loop counter i the instant you match. If the loop finishes without returning, you fall through to a final return -1. Because no real index is -1, the calling code can test for it cleanly.
- Loop by index with range(len(prices))
- Compare prices[i] to target
- Return i on the first match
- Return -1 after the loop (not found)
- Same shape as find_index
- Loop with range(len(seats))
- Return i on match, -1 after loop
- No real Python list index is -1 (indices start at 0).
- So -1 is a perfect sentinel meaning "not found".
- The calling code tests:
if find_index(...) != -1:
Returning the Position
12.4 WHILE Loop and Pseudocode
Here the loop keeps going while there are elements left and we have not found the target yet. The condition does double duty: it stops at the end of the list, and it stops early on success.
def find_index(data, target):
index = 0
found = False
while index < len(data) and not found:
if data[index] == target:
found = True
else:
index = index + 1
if found:
return index
else:
return -1- Only move the index forward in the
elsebranch. - If you increase index after finding the target, you will return the wrong index (one past the match).
Cambridge pseudocode — WHILE loop
Index <- 0
Found <- FALSE
WHILE Index < Size AND Found = FALSE
IF List[Index] = SearchValue THEN
Found <- TRUE
ELSE
Index <- Index + 1
ENDIF
ENDWHILE
IF Found = TRUE THEN
OUTPUT "Found at position ", Index
ELSE
OUTPUT "Value not found"
ENDIF- Flag starts FALSE, Index starts 0
- WHILE Index < Size AND Found = FALSE
- Compare List[Index] to SearchValue inside the loop
- Increment Index in the ELSE branch
- After the loop, check Found and output
- Start Index ← 0, Found ← FALSE
- REPEAT: compare, increment Index
- UNTIL Found = TRUE OR Index > MaxIndex
- Note: Index - 1 is the found position (Index was incremented past it)
WHILE Loop & Pseudocode
12.5 Efficiency and Big O
The cost of a linear search is measured in comparisons. There are three cases worth knowing:
| Case | Position of target | Comparisons |
|---|---|---|
| Best case | First element | 1 |
| Worst case | Last element, or not present | n (for n items) |
| Average case | Somewhere in the middle | ~n/2 |
n (n comparisons for n items), we say a linear search is O(n).- Linear search is O(n)
- Doubling the data doubles the time
- 1000 items → 1ms
Efficiency and Big O
12.6 Full Exam-Style Question
A clinic stores the appointment ID numbers booked for one day in a global 1D array bookings. The IDs are added in the order patients call, so they are not sorted.
bookings = [5081, 5044, 5119, 5007, 5066, 5093, 5012, 5070]- Write a function
search_booking(wanted)that performs a linear search on the global arraybookingsand returns the index ofwanted, or -1 if it is not found. - The main program should ask the user for an ID, call the function, and print "Found at position X" or "Not found".
- Function loops by index with range(len(bookings))
- Compare bookings[i] to wanted
- Return i on match, return -1 after loop
- Main program: input, call function, check result
✓ Key Points Summary
12.7 Practice Tasks
Fifteen exam-style linear search tasks. Each shows only the question — click Hint for the thought process, or Help for the worked solution.
- For every linear search task, the marker checks: (1) correct loop over all elements, (2) comparison of each element to target, (3) early exit on match (break or return), (4) handling both "found" and "not found" outcomes.
- The most common mark loss is not handling the "not found" case.
Question Bank
Answer all questions, then press Submit Quiz to see your score.
Question 1Multiple Choice
What does a linear search do?
Question 2True / False
A linear search requires the data to be sorted.
Question 3Multiple Choice
What is the Big O of a linear search?
Question 4Multiple Choice
What does find_index return if the target is not found?
Question 5True / False
In the FOR loop + flag pattern, found starts as False.
Question 6Multiple Choice
Which loop form returns the index of a match?
Question 7Multiple Choice
In the WHILE loop version, when do you increment the index?
Question 8True / False
The best case for a linear search is 1 comparison (target is first).
Question 9Multiple Choice
What is the worst case for a linear search of n items?
Question 10Multiple Choice
What does break do in a linear search?
Question 11True / False
A linear search returns the index of the FIRST match, not the last.
Question 12Multiple Choice
If 1000 items take ~1ms, how long do 2000 items take (worst case)?
Answer all 12 questions to enable submission.