Linear Search (College Board AP® Computer Science Principles): Revision Note
Linear search
What is a linear search?
A linear search (also called a sequential search) checks each element in a list one at a time, from beginning to end, until the target value is found or the end of the list is reached
It is the simplest search algorithm and works on both sorted and unsorted lists
How a linear search works
A linear search uses a
foundflag, initialized tofalse, to track whether the target has been locatedThe loop checks each element in turn; if a match is found the flag is set to
trueAfter the loop completes, the flag determines what the program displays
found ← false
FOR EACH item IN list
{
IF(item = target)
{
found ← true
}
}
IF(found = true)
{
DISPLAY("Found")
}
ELSE
{
DISPLAY("Not found")
}
Linear search characteristics
Best case: the target is the first element (1 comparison)
Worst case: the target is the last element or not in the list (n comparisons, where n is the length of the list)
The number of comparisons grows in proportion to the size of the list
Linear search does not require the list to be sorted
Characteristic | Detail | Example |
|---|---|---|
Data requirement | Works on sorted or unsorted lists | Can search |
Best case | 1 comparison — target is the first element | Searching for 8 in |
Worst case | n comparisons — target is last or not in the list | Searching for 12 in |
Examiner Tips and Tricks
In code trace questions, track the found flag through each iteration and identify which element triggers it being set to
true.For the CPT, if your program searches a list, a linear search is the most straightforward approach to implement and explain in your written response.
Worked Example
A list contains the following values:
[8, 3, 15, 7, 12]
A linear search is performed to find the value 7. How many comparisons are made before the value is found?
(A) 2
(B) 3
(C) 4
(D) 5
[1]
Answer:
(C) 4 [1 mark]
The search checks elements in order: 8, 3, 15, then 7; the target is found on the fourth comparison
Unlock more, it's free!
Was this revision note helpful?