- Understand how linear search applies the prescribed array-traversal algorithm
- Understand how the linear search algorithm works step by step
- Implement linear search using both pseudocode and Python
- I can name the three prescribed N5 standard algorithms and explain where linear search fits
- I can trace through a linear search, showing the value of
foundandpositionat each step - I can explain what happens when the target is found and when it is not found
- I can write Python code and N5 pseudocode for a linear search
- I can identify and correct a common error in a linear search implementation
Answer before the lesson begins. These check prior knowledge from SDD12 — it's fine if you're unsure.
1. Given scores = [45, 92, 78, 61, 83], what is the value of scores[2]?
2. A program runs for index in range(len(data)): where data = [10, 20, 30, 40]. How many times does the loop body execute?
3. Which data type stores only the values True or False?
Key vocabulary
False, that is set to True when the target is located during the search.-1 before the search begins to indicate "not yet found".Array traversal application: linear search
Where linear search fits at N5
In programming, the same types of problems come up again and again: searching for a value in a list, finding the largest number, and counting how many items meet a condition. Programmers use well-tested, reusable patterns instead of inventing the same logic from scratch each time.
The N5 specification names exactly three standard algorithms:
- Input validation
- A running total within a loop
- Traversing a one-dimensional array
Linear search is not a separately named N5 standard algorithm. It is a useful application pattern built from the prescribed array traversal: visit each element in order and compare it with a target. This lesson gives extra practice with traversal, selection, Boolean flags, and positions.
The idea behind linear search
Imagine you have a list of 100 unsorted student scores written on separate slips of paper. You want to know if a particular score — say, 87 — is in the list, and if so, which slip it is on. The only reliable way is to check each slip, one at a time, until you either find 87 or reach the end of the list without finding it. That is exactly what a linear search does.
"Linear" means in a straight line — the algorithm processes elements sequentially, from the first to the last, without skipping. It does not require the array to be sorted, which makes it very flexible. The downside is that in the worst case (target not present or at the very end) it must check every element.
The two variables: found and position
A linear search uses two key variables set up before the loop begins:
found— a Boolean variable, initialised toFalse. It becomesTrueas soon as the target is located.position— an integer variable, initialised to-1. It is updated to the index where the target is found. Keeping it as-1after the loop means the target was never found.
Using -1 as the "not found" sentinel is a common convention in programming: it is an impossible array index (valid indices are 0 or greater), so it clearly signals "no match was found".
How the algorithm works — step by step
The loop visits every element from index 0 to the last index. On each iteration it compares the current element with the target. If they match, found is set to True and position is updated. After the loop, the values of found and position are used to print the result.
Note that the basic N5 version uses a fixed FOR loop and does not stop early when the target is found — it continues checking all remaining elements. The values of found and position simply stay as they were once the target is located.
Python implementation
Here is the complete Python code for a linear search:
array = [85, 72, 91, 68, 88]
target = 91
found = False
position = -1
for index in range(len(array)):
if array[index] == target:
found = True
position = index
if found:
print("Found at position", position)
else:
print("Not found")
When this code runs, index takes values 0, 1, 2, 3, 4 in turn. At index = 2, array[2] equals 91 which matches target, so found becomes True and position is set to 2. The loop continues for indices 3 and 4 but no further matches occur. After the loop, the output is: Found at position 2.
N5 pseudocode — exam format
In the SQA exam, pseudocode uses specific keywords. The linear search in N5 pseudocode looks like this:
SET array TO [85, 72, 91, 68, 88]
SET target TO 91
SET found TO false
SET position TO -1
FOR index FROM 0 TO LEN(array) - 1 DO
IF array[index] = target THEN
SET found TO true
SET position TO index
END IF
END FOR
IF found = true THEN
SEND "Found at position " & position TO DISPLAY
ELSE
SEND "Not found" TO DISPLAY
END IF
Key differences from Python: use SET ... TO instead of = for assignment; use IF ... THEN ... END IF; use FOR index FROM 0 TO LEN(array) - 1 DO ... END FOR; use SEND ... TO DISPLAY instead of print(); use = (not ==) for comparison. The & symbol joins strings together.
Reading a trace table
Exam questions often ask you to trace a linear search — that means working through the algorithm by hand and recording the values of key variables at each step. A trace table is a grid showing the index, the array value at that index, whether it matches the target, and the current values of found and position.
When completing a trace table, work through every iteration even if the target has already been found — the basic FOR loop does not stop early, so you must show all rows.
Worked examples
Trace a linear search for the value 52 in the array [34, 17, 52, 8, 73].
found = False and position = -1. The target is 52.| index | array[index] | Match (== 52)? | found | position |
|---|---|---|---|---|
| 0 | 34 | No | False | -1 |
| 1 | 17 | No | False | -1 |
| 2 | 52 | Yes | True | 2 |
| 3 | 8 | No | True | 2 |
| 4 | 73 | No | True | 2 |
found = True, so the output is: Found at position 2. Note that the loop continued for indices 3 and 4 even though the target had already been found at index 2.Trace a linear search for the value 99 in the same array [34, 17, 52, 8, 73].
found = False, position = -1. Target is 99.| index | array[index] | Match (== 99)? | found | position |
|---|---|---|---|---|
| 0 | 34 | No | False | -1 |
| 1 | 17 | No | False | -1 |
| 2 | 52 | No | False | -1 |
| 3 | 8 | No | False | -1 |
| 4 | 73 | No | False | -1 |
found is still False and position is still -1. The output is: Not found. Every element was compared — there is no way to know whether 99 is absent without checking everything.Write Python code to search for the name "Charlie" in the array ["Alice", "Bob", "Charlie", "David", "Eve"] and display the position if found.
array[index] == target works the same way for strings in Python.names = ["Alice", "Bob", "Charlie", "David", "Eve"]
target = "Charlie"
found = False
position = -1
for index in range(len(names)):
if names[index] == target:
found = True
position = index
if found:
print("Found at position", position)
else:
print("Not found")
Found at position 2.Write N5 pseudocode to search for the score 80 in an array of six test scores: [65, 80, 72, 91, 80, 58]. Note: 80 appears twice — the algorithm records the position of the last occurrence because the loop does not stop at the first match.
SET scores TO [65, 80, 72, 91, 80, 58]
SET target TO 80
SET found TO false
SET position TO -1
FOR index FROM 0 TO LEN(scores) - 1 DO
IF scores[index] = target THEN
SET found TO true
SET position TO index
END IF
END FOR
IF found = true THEN
SEND "Found at position " & position TO DISPLAY
ELSE
SEND "Not found" TO DISPLAY
END IF
Found at position 4. (The last match wins in a basic linear search.)A linear search is performed on the array [48, 15, 63, 7, 29, 41], looking for the target value 7.
Answer the following without running the code:
- How many comparisons are made before the target is found (i.e. how many times is the condition
array[index] == 7evaluated as True or False)? - What are the values of
foundandpositionimmediately after the loop finishes? - What does the algorithm display as its final output?
- 4 comparisons before the target is found. The condition is tested at index 0 (48 ≠ 7), index 1 (15 ≠ 7), index 2 (63 ≠ 7), and index 3 (7 = 7, match found). The loop then continues for indices 4 and 5 — 2 more comparisons — making 6 comparisons in total across the whole loop. The question asks specifically about before finding the target, which is 4.
found = True,position = 3. The match at index 3 sets both variables; iterations 4 and 5 find no further matches so these values are not changed.- The algorithm displays:
Found at position 3.
for index in range(1, len(array)): skips the first element entirely. If the target happens to be at index 0, the algorithm reports "Not found" even though it is there. Always start at index 0.if array[index] = target: causes a SyntaxError — a single = is assignment, not comparison. In Python, comparison always uses ==. (In pseudocode, a single = is correct for comparison.)if found ... else ... block after the loop.FOR index FROM 0 TO LEN(array) DO goes one step too far — valid indices are 0 to LEN(array) - 1. An array of 5 elements has indices 0, 1, 2, 3, 4; accessing index 5 is out of bounds.found and position before the loop. If these variables are not set before the loop starts, Python will raise a NameError when the if found: line is reached (because the variable does not exist if no match was ever found inside the loop).Linear search is useful practice for questions that ask you to trace an array traversal. Always show every iteration — even after the target is found, the basic FOR loop keeps going, so you must complete all rows of the trace table. When writing pseudocode, double-check: FOR index FROM 0 TO LEN(array) - 1 DO — the - 1 is essential. If the question uses the word "identify", state the index or variable value clearly. If it says "explain", add a reason — for example, "because the loop has checked every element without finding a match."
Questions 1–5 are auto-checked. Questions 6–8 are self-marked — write your answer, then reveal the model answer to check your work. Questions 9–10 are practical PyCharm implementation tasks.
1. What does a linear search algorithm do? TYPE 1
2. What value should the found variable be set to before a linear search begins? TYPE 1
3. An array has 8 elements. A linear search looks for a value that is not in the array. How many comparisons does the algorithm make in total? TYPE 1
4. Given numbers = [10, 25, 30, 15, 45], a linear search for the value 30 is performed. At which index is the match found? TYPE 1
5. After a linear search completes and the target was not found, what are the values of found and position? TYPE 1
6. Trace a linear search for the value 15 in the array [20, 15, 40, 5, 30]. Complete a trace table showing: index, array[index], whether the match condition is True or False, found, and position after each iteration. State the final output. TYPE 2
Initialise: found = False, position = -1, target = 15.
| index | array[index] | Match (== 15)? | found | position |
|---|---|---|---|---|
| 0 | 20 | No | False | -1 |
| 1 | 15 | Yes | True | 1 |
| 2 | 40 | No | True | 1 |
| 3 | 5 | No | True | 1 |
| 4 | 30 | No | True | 1 |
Final output: Found at position 1
7. Explain why a basic linear search (using a FOR loop) continues checking elements even after it has already found the target. What change to the algorithm would allow it to stop as soon as the target is located? TYPE 2
The basic N5 version uses a fixed FOR loop that always runs from index 0 to the end of the array. Once the loop starts, it completes all iterations regardless of what happens inside — there is no mechanism to exit early. When a match is found, found and position are updated, but the loop carries on to the remaining elements (finding no further matches, so the variables stay as they were).
To stop early, the FOR loop would be replaced with a conditional (WHILE) loop that checks whether the target has been found on each iteration: while index < len(array) and not found:. As soon as found becomes True, the condition fails and the loop exits — fewer comparisons are made on average. This is known as an early-exit or short-circuit linear search, but it is not required at N5.
8. Write Python code for a linear search program that: stores 6 integer values in an array; asks the user to enter a number to search for; performs a linear search; prints Found at position X or Not found. TYPE 2
scores = [45, 72, 88, 61, 93, 50]
target = int(input("Enter a score to find: "))
found = False
position = -1
for index in range(len(scores)):
if scores[index] == target:
found = True
position = index
if found:
print("Found at position", position)
else:
print("Not found")
Any six-element array of integers is acceptable. The int(input(...)) converts the user's string input to an integer so it can be compared with the integer values in the array.
9. Practical: In PyCharm, create a new Python file called sdd13_linear_search.py. Store [45, 72, 88, 61, 93, 50], ask for a target, perform a linear search, and display Found at position X or Not found. Test with targets 88 and 40, and record both outputs. TYPE 3
scores = [45, 72, 88, 61, 93, 50]
target = int(input("Enter a score to find: "))
found = False
position = -1
for index in range(len(scores)):
if scores[index] == target:
found = True
position = index
if found:
print("Found at position", position)
else:
print("Not found")
Exact expected outputs:
Target 88 → Found at position 2 Target 40 → Not found
10. Practical: In sdd13_linear_search.py, replace the previous program with a linear search of ["Glasgow", "Edinburgh", "Dundee", "Aberdeen", "Inverness"]. Ask for a city and display its position or Not found. Test with Edinburgh and Perth, and record both outputs. TYPE 3
cities = ["Glasgow", "Edinburgh", "Dundee", "Aberdeen", "Inverness"]
target = input("Enter a city to find: ")
found = False
position = -1
for index in range(len(cities)):
if cities[index] == target:
found = True
position = index
if found:
print("Found at position", position)
else:
print("Not found")
Exact expected outputs:
Edinburgh → Found at position 1 Perth → Not found
Suggested timing: 60 minutes. Warm up 10 min; notes + vocabulary 15 min; worked examples 15 min; now you try 5 min; task set 15 min.
Key misconception to address: Pupils often think the algorithm stops as soon as it finds the target. Make explicit that the basic FOR loop runs to completion regardless — the variables are simply not updated again after the match. Draw this out on the board by continuing the trace table past the match row. If pupils ask why it keeps going, this is a great opportunity to preview the WHILE-based early-exit version (not examinable at N5, but satisfying as an explanation).
Live demo suggestion: Open a Python REPL and build the linear search live. First enter just the loop and add a print(index, array[index]) inside so pupils can watch each comparison happen. Then add the if block and the found flag. Run it with a target that is present, then with one that is absent. Finally, deliberately introduce the off-by-one error (range(1, len(array))) and challenge the class to spot why the result is wrong when the target is at index 0.
Extension question: Ask pupils how the algorithm would need to change if the array could contain duplicates and you wanted to find all positions where the target appears (not just the last one). Guide them towards accumulating positions into a second array or printing each match inside the loop.
SQA command words covered: "trace" (Q6, Now You Try), "explain" (Q7), "write" (Q8, Q9), "identify" (Q10).