- Understand what a standard algorithm is and why programmers use them
- Understand how the linear search algorithm works step by step
- Implement linear search using both pseudocode and Python
- I can explain what a standard algorithm is and give an example
- 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 i 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".Standard algorithms: linear search
What is a standard algorithm?
In programming, the same types of problems come up again and again: searching for a value in a list, finding the largest number, counting how many items meet a condition. Rather than solving these problems from scratch every time, computer scientists have developed standard algorithms — well-tested, widely understood solutions that every programmer knows.
At N5 level, you are expected to know three standard algorithms:
- Linear search — find a specific value in an array (this lesson)
- Finding the minimum and maximum — identify the smallest or largest value
- Counting occurrences — count how many elements meet a condition
For each algorithm, you must be able to: explain how it works, trace through it on a given array, and write it in both Python and N5 pseudocode.
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 i in range(len(array)):
if array[i] == target:
found = True
position = i
if found:
print("Found at position", position)
else:
print("Not found")
When this code runs, i takes values 0, 1, 2, 3, 4 in turn. At i = 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[i] == target works the same way for strings in Python.names = ["Alice", "Bob", "Charlie", "David", "Eve"]
target = "Charlie"
found = False
position = -1
for i in range(len(names)):
if names[i] == target:
found = True
position = i
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[i] == 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 i 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[i] = 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).SQA questions on linear search most commonly ask you to trace the algorithm. 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. Forgetting the final rows is a common way to lose marks. When writing pseudocode, double-check: FOR index FROM 0 TO LEN(array) - 1 DO — the - 1 is essential and is often omitted under exam pressure. 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–10 are self-marked — write your answer, then reveal the model answer to check your work.
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 i < 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 i in range(len(scores)):
if scores[i] == target:
found = True
position = i
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. Write N5 pseudocode for a linear search that looks for the string "Edinburgh" in this array of city names: ["Glasgow", "Edinburgh", "Dundee", "Aberdeen", "Inverness"]. TYPE 2
SET cities TO ["Glasgow", "Edinburgh", "Dundee", "Aberdeen", "Inverness"]
SET target TO "Edinburgh"
SET found TO false
SET position TO -1
FOR index FROM 0 TO LEN(cities) - 1 DO
IF cities[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
Output: Found at position 1 (Edinburgh is at index 1).
10. The pseudocode below contains an error. Identify the error, explain what goes wrong when the algorithm runs, and write the corrected line.
SET scores TO [67, 82, 45, 91, 58]
SET target TO 91
SET found TO false
SET position TO -1
FOR index FROM 1 TO LEN(scores) - 1 DO
IF scores[index] = target THEN
SET found TO true
SET position TO index
END IF
END FOR
TYPE 2
Error: The loop starts FROM 1 instead of FROM 0.
Effect: The first element, scores[0] (the value 67), is never compared with the target. If the target were 67, the algorithm would incorrectly report "Not found". In this example, 91 is at index 3, so it would still be found — but the algorithm is always wrong for any target stored at index 0.
Corrected line: FOR index FROM 0 TO LEN(scores) - 1 DO
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(i, array[i]) 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).