Searching, Sorting & Hashing

Linear Search

The simplest search algorithm — check each item in turn until the target is found. FOR loop + flag, returning the index (-1 if not found), WHILE loop version, Cambridge pseudocode, and Big O efficiency (O(n)).

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.
Key rule:
  • 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.

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.

Interactive Simulator

Simulation

Target:53
42
0
17
1
88
2
53
3
9
4
61
5

Status: Click Start to begin the simulation.

Code

1found = False
2for i in range(len(data)):
3 if data[i] == target:
4 found = True
5 break
6if found:
7 print("Found")
8else:
9 print("Not found")
Speed:

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")
Key rule — always handle both outcomes:
  • 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.
Your Turn — is_present — return True/False [4 marks]
Write program code for a function is_present(data, target) that performs a linear search and returns True if target is in the list data, or False if it is not.
Hint:
  • 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)
Your Turn — contains_temp — temperatures
Write a function contains_temp(readings, target) that returns True if target is in the list readings, or False if it is not.
Hint:
  • Same pattern: header, loop, compare, return early on match
  • Return False after the loop
Your Turn — Count comparisons
Using a flag, count how many comparisons a linear search makes to find 9 in [4, 8, 9, 2].
Hint:
  • Index 0: 4 is not 9 (1 comparison)
  • Index 1: 8 is not 9 (2 comparisons)
  • Index 2: 9 = 9 — stop (3 comparisons)
Your Turn
How many comparisons to find 5 in [7, 1, 5, 5, 9]?
Hint:
  • A linear search stops at the first match
  • Check each index from 0
  • The duplicate 5 at index 3 is never reached
Your Turn — Trace the flag
What does this loop print for nums = [3, 6, 1], target = 8? found = False for v in nums: if v == target: found = True print(found)
Hint:
  • 8 is not in the list
  • The flag never changes from False
Your Turn
Using the same code, what prints for nums = [3, 6, 1], target = 6?
Hint:
  • Does the flag ever switch to True?
  • 6 is at index 1

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.

Your Turn — find_index — return the index [5 marks]
Write program code for a function find_index(prices, target) that returns the index of the first element equal to target, or -1 if target is not in prices.
Hint:
  • 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)
Your Turn — seat_position — find a seat
Write a function seat_position(seats, wanted) that returns the index of the first seat equal to wanted, or -1 if not found.
Hint:
  • Same shape as find_index
  • Loop with range(len(seats))
  • Return i on match, -1 after loop
Why -1 is safe:
  • 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:

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
Key rule — only increment in the else branch:
  • Only move the index forward in the else branch.
  • 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
Your Turn — Complete the pseudocode [4 marks]
Complete the pseudocode so it performs a linear search of List for SearchValue and outputs the position, or a "not found" message.
Hint:
  • 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
Your Turn — REPEAT...UNTIL version
Write pseudocode using REPEAT...UNTIL to search Codes for Wanted. Output the position or "not found".
Hint:
  • 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)

12.5 Efficiency and Big O

The cost of a linear search is measured in comparisons. There are three cases worth knowing:

CasePosition of targetComparisons
Best caseFirst element1
Worst caseLast element, or not presentn (for n items)
Average caseSomewhere in the middle~n/2
Key rule — O(n): Because the worst case grows directly with n (n comparisons for n items), we say a linear search is O(n).
Your Turn — Doubling the data
A linear search of 1000 items takes about 1 millisecond in the worst case. Roughly how long would 2000 items take in the worst case?
Hint:
  • Linear search is O(n)
  • Doubling the data doubles the time
  • 1000 items → 1ms

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]
Task — search_booking [6 marks]
  • Write a function search_booking(wanted) that performs a linear search on the global array bookings and returns the index of wanted, 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".
Your Turn — Model solution
Click Show Answer to see the full model solution for search_booking and the main program.
Hint:
  • 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

A linear search checks each element in turn from index 0 to the end.
Use it when data is unsorted, the list is small, or simplicity matters.
Linear search does NOT require sorted data (unlike binary search).
FOR loop + flag: found = False, loop, if match set found = True and break, check after loop.
Alternative: return True on match (exits function early), return False after loop.
To return the index: use range(len(list)), return i on match, return -1 after loop.
-1 is a safe "not found" sentinel because no real index is -1.
WHILE loop version: while index < len(data) and not found — increment only in else branch.
Pseudocode: Found ← FALSE, WHILE Index < Size AND Found = FALSE, compare, increment or set Found.
Always handle both outcomes: "found" and "not found".
Best case: 1 comparison (target is first). Worst case: n comparisons (last or not present).
Average case: ~n/2 comparisons.
Big O: O(n) — the worst case grows directly with n.
break stops the search early when the target is found.

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.

Exam tip:
  • 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.
1Practice Task — is_present — True/False [4 marks]
Write a function is_present(data, target) that returns True if target is in data, or False if not. Use a linear search.
2Practice Task — find_index — return position [5 marks]
Write a function find_index(data, target) that returns the index of the first match, or -1 if not found.
3Practice Task — FOR loop + flag [4 marks]
Write code that searches [42, 17, 88, 53, 9, 61] for 53 using a flag (found). Print "Found" or "Not found".
4Practice Task — WHILE loop version [5 marks]
Write a function find_while(data, target) that uses a WHILE loop with a flag to return the index, or -1.
5Practice Task — Pseudocode WHILE search [4 marks]
Write pseudocode to search List for SearchValue using a WHILE loop. Output the position or "not found".
6Practice Task — Count comparisons [2 marks]
How many comparisons does a linear search make to find 9 in [4, 8, 9, 2]?
7Practice Task — Best, worst, average [3 marks]
For a linear search of n items, state the best case, worst case, and average case number of comparisons.
8Practice Task — Big O notation [2 marks]
What is the Big O notation for a linear search, and why?
9Practice Task — Doubling the data [2 marks]
If 1000 items take ~1ms (worst case), how long do 2000 items take?
10Practice Task — Search a string list [4 marks]
Write a function find_name(names, target) that returns the index of target in a list of names, or -1.
11Practice Task — Why -1 is safe [2 marks]
Why is -1 a safe "not found" value to return from a search over a Python list?
12Practice Task — REPEAT...UNTIL pseudocode [5 marks]
Write pseudocode using REPEAT...UNTIL to search Codes for Wanted. Output the position or "not found".
13Practice Task — Search with global array [6 marks]
Write a function search_booking(wanted) that searches a global array bookings and returns the index or -1. Include a main program that asks for an ID and prints the result.
14Practice Task — Linear vs binary [2 marks]
State one situation where a linear search is preferred over a binary search.
15Practice Task — Trace the flag [3 marks]
For nums = [3, 6, 1] and target = 8, what does this print? found = False for v in nums: if v == target: found = True print(found)

Question Bank

Answer all questions, then press Submit Quiz to see your score.

0/12 answered

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.