🔒
Pro Content
Subscribe to access all 69 OCR H446 A Level lessons.
£7.99/month
or £59/year
Subscribe now →
🔒 Pro · Component 2 · 2.2.1 Problem Solving & Programming
2.2.1e Writing and Tracing Algorithms
OCR H446 · A Level Computer Science · ~20 min read
Notes
Video
Slides
Worksheet
Quiz

Writing Algorithms in Pseudocode

Pseudocode is an informal, language-independent description of an algorithm's logic. It uses structured English with programming constructs but doesn't need to compile. OCR H446 uses a specific pseudocode style in the exam.

Key OCR Pseudocode Conventions

// Variables and assignment
x ← 5
name ← "Alice"

// Input / Output
x ← userinput
print(x)

// Selection
if x > 0 then
    print("positive")
elseif x < 0 then
    print("negative")
else
    print("zero")
endif

// Count-controlled loop
for i ← 1 to 10
    print(i)
next i

// Condition-controlled loop
while x > 0
    x ← x - 1
endwhile

// Subroutine (function)
function square(n)
    return n * n
endfunction

result ← square(5)   // result = 25

Arrays in Pseudocode

// 1D array (0-indexed)
scores ← [10, 20, 30, 40, 50]
print(scores[0])     // 10

// Iterating
for i ← 0 to length(scores) - 1
    print(scores[i])
next i

// 2D array
grid ← [[1,2,3],[4,5,6],[7,8,9]]
print(grid[1][2])    // 6 (row 1, column 2)

Trace Tables

A trace table (dry run) is a manual step-by-step execution of an algorithm, recording the value of each variable at each step. Used to check correctness, find bugs, and answer exam questions.

How to construct a trace table:

  • Create columns for each variable used in the algorithm
  • Add an Output column if the algorithm prints values
  • Execute each line, recording any variable change in the row
  • If a variable doesn't change on a step, leave the cell blank

Example: trace the following for input n=5

total ← 0
for i ← 1 to n
    total ← total + i
next i
print(total)
StepitotalOutput
total ← 00
i ← 11
total ← 0+11
i ← 22
total ← 1+23
i ← 33
total ← 3+36
i ← 44
total ← 6+410
i ← 55
total ← 10+515
print(total)15

Big O Notation (Algorithm Complexity)

Big O notation describes how an algorithm's time (or space) requirements grow as input size n increases. It expresses the worst-case upper bound, ignoring constants and lower-order terms.

NotationNameExamplen=1000 approx.
O(1)ConstantArray index lookup, hash table get1 operation
O(log n)LogarithmicBinary search~10 operations
O(n)LinearLinear search, single loop1,000
O(n log n)LinearithmicMerge sort, heapsort~10,000
O(n²)QuadraticBubble sort, insertion sort (worst), nested loops1,000,000
O(2ⁿ)ExponentialBrute-force subset sum, naive FibonacciAstronomical
O(n!)FactorialBrute-force TSPImpossible

Identifying Big O from Code

# O(1) — no loops, just assignments/comparisons
def get_first(arr):
    return arr[0]

# O(n) — one loop through all elements
def linear_search(arr, target):
    for item in arr:          # n iterations
        if item == target:
            return True
    return False

# O(n²) — nested loops, both depending on n
def bubble_sort(arr):
    for i in range(len(arr)):           # n
        for j in range(len(arr)-i-1):  # n
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]

# O(log n) — halves the problem each step
def binary_search(arr, target):
    low, high = 0, len(arr)-1
    while low <= high:                    # log n iterations
        mid = (low + high) // 2
        if arr[mid] == target: return mid
        elif arr[mid] < target: low = mid + 1
        else: high = mid - 1
    return -1

Best, Worst, and Average Case

Best caseWorst caseAverage case
Linear searchO(1) — target at index 0O(n) — target at end or absentO(n/2) = O(n)
Binary searchO(1) — target is midpointO(log n) — search exhaustedO(log n)
Bubble sortO(n) — already sorted (with flag)O(n²) — reverse sortedO(n²)
Merge sortO(n log n)O(n log n)O(n log n)
Quick sortO(n log n) — balanced pivotsO(n²) — already sorted, worst pivotO(n log n)
Exam tip: When asked for complexity, drop constants: O(2n) → O(n), O(n² + n) → O(n²). Big O captures the dominant term as n→∞. Examiners want the simplified form.
Exam tip: Trace table exam tips — record EVERY change to every variable. If a variable stays the same, leave the cell blank (don't repeat the old value). Follow the algorithm exactly — don't try to "shortcut" mentally.
✓ Notes completed!
Video coming soon
Click to advance · Arrow keys also work
Click slide or press arrow keys to navigate

Worksheet — 2.2.1e Writing & Tracing Algorithms

8 questions · 26 marks · instantly marked

Q1Write pseudocode for a function max_value(arr) that returns the largest value in an array. Assume the array has at least one element.[4 marks]
✓ Mark scheme
function max_value(arr) [1 — correct function definition]
    max ← arr[0] [1 — initialise max to first element, not 0]
    for i ← 1 to length(arr) - 1 [1 — loop from index 1 (or 0) to end]
        if arr[i] > max then
            max ← arr[i]
        endif
    next i
    return max [1 — returns max]
endfunction
Note: initialising max to 0 loses 1 mark if array could have all-negative values.
Q2Trace the following pseudocode for input n=4 and produce a trace table:
result ← 1
for i ← 1 to n
    result ← result * i
next i
print(result)
[5 marks]
✓ Mark scheme
Headers: i, result, Output [1]. Correct rows:
result ← 1 → result=1
i=1 → result=1×1=1
i=2 → result=1×2=2
i=3 → result=2×3=6
i=4 → result=6×4=24 [3 — award 1 for each correct pair of i/result values]
print: Output=24 [1]. This computes 4! = 24. Algorithm calculates n factorial.
Q3State the time complexity (Big O) of the following and justify: (a) a single loop from 1 to n; (b) two nested loops both from 1 to n; (c) binary search on a sorted array.[3 marks]
✓ Mark scheme
(a) O(n) — the loop body executes exactly n times; one operation per iteration [1]. (b) O(n²) — the outer loop runs n times; for each, the inner loop runs n times; total = n × n = n² operations [1]. (c) O(log n) — binary search halves the search space at each step; after k steps the space is n/2ᵏ; total steps ≈ log₂n [1].
Q4Write pseudocode for linear search that takes an array and a target value, and returns the index of the target (or -1 if not found).[3 marks]
✓ Mark scheme
function linear_search(arr, target) [0.5]
    for i ← 0 to length(arr) - 1 [1 — iterates entire array]
        if arr[i] = target then [0.5 — correct comparison]
            return i [0.5 — returns index]
        endif
    next i
    return -1 [0.5 — returns -1 if not found]
endfunction
Q5Explain what Big O notation represents. Why do we drop constants and lower-order terms (e.g., O(3n + 5) → O(n))?[3 marks]
✓ Mark scheme
Big O notation describes the upper bound on an algorithm's time (or space) complexity as input size n grows [1]. It classifies algorithms by how fast their requirements grow with n. Constants are dropped because they represent machine-specific factors (hardware speed, language overhead) and become insignificant for large n [1]. Lower-order terms are dropped because as n→∞, the dominant term overwhelms them: for O(n²+n), when n=1000, n²=1,000,000 and n=1000 — n is only 0.1% of n². The dominant term determines scalability [1].
Q6Trace the following pseudocode and state what the algorithm does:
arr ← [3, 1, 4, 1, 5]
for i ← 0 to 3
    for j ← 0 to 3 - i
        if arr[j] > arr[j+1] then
            temp ← arr[j]
            arr[j] ← arr[j+1]
            arr[j+1] ← temp
        endif
    next j
next i
[4 marks]
✓ Mark scheme
Algorithm: bubble sort [1]. Pass i=0: compare pairs (3,1)→swap=[1,3,4,1,5]; (3,4)→no swap; (4,1)→swap=[1,3,1,4,5]; (4,5)→no swap. arr=[1,3,1,4,5] [1]. Pass i=1: (1,3)→no; (3,1)→swap=[1,1,3,4,5]; (3,4)→no. arr=[1,1,3,4,5] [1]. Pass i=2: (1,1)→no; (1,3)→no. Pass i=3: (1,1)→no. Final: [1,1,3,4,5] [1]. Time complexity: O(n²).
Q7Explain the difference between best-case, worst-case and average-case time complexity. Give examples for linear search.[3 marks]
✓ Mark scheme
Best case: the most favourable input for the algorithm — fewest operations needed. For linear search: target is at index 0 → O(1) [1]. Worst case: the most unfavourable input — most operations needed. For linear search: target is at last index or not present → O(n) [1]. Average case: the expected performance over all possible inputs assuming a uniform distribution. For linear search: target is found halfway through on average → O(n/2) = O(n) [1]. Big O typically refers to worst case unless stated otherwise.
Q8Write pseudocode for binary search on a sorted array. State its time complexity and explain why it achieves this.[5 marks]
✓ Mark scheme
function binary_search(arr, target) [0.5]
    low ← 0 [0.5 — initialise low and high]
    high ← length(arr) - 1
    while low ≤ high [1 — correct loop condition]
        mid ← (low + high) DIV 2 [0.5 — correct midpoint]
        if arr[mid] = target then return mid [0.5 — found case]
        elseif arr[mid] < target then low ← mid + 1 [0.5 — search right]
        else high ← mid - 1 [0.5 — search left]
        endif
    endwhile
    return -1 [0.5 — not found]
endfunction
Complexity: O(log n) [0.5]. Each iteration halves the search space. After k iterations, remaining size is n/2ᵏ. Terminates when this reaches 1: k = log₂n [1].
Topic Quiz
1 of 15
You scored
out of 15
🎯

Mini Test — 2.2.1e Writing & Tracing Algorithms

  • 10 questions · 10 marks · 10 minutes
  • 5 MCQ + 5 short answer
Card 1 of 15
Click to reveal
🎉
Complete!
TermDefinition
← 2.2.1d Computational Methods 2.2.1 Problem Solving & Programming Next: 2.2.1f Modular Design & Standard Algorithms →