โ† Back to subjects
โญ 0
OCR A-level Computer Science (H446) ยท Algorithms
Mini-Lesson

Algorithms

This mini-lesson covers OCR 2.3 โ€” Algorithms: the standard algorithms you must be able to trace, code and โ€” the part that separates the top grades โ€” compare by complexity.

  • Big-O โ€” time and space complexity
  • Searching โ€” linear, binary, binary tree
  • Sorting โ€” bubble, insertion, merge, quick
  • Traversal โ€” breadth-first and depth-first
  • Dijkstra and A* path finding

Work through each screen, answer the questions as you go (some are recall, some are calculations you must actually work out) and collect โญ stars. Press Start when you're ready.

2.3 ยท Complexity

Big-O โ€” time and space

Big-O describes how an algorithm's cost grows with the input size n. Constants and lower-order terms are dropped, because for large n they cease to matter.

3nยฒ + 500n + 9000 โ†’ O(nยฒ)
OrderNameExample
O(1)constantarray access, hash lookup
O(log n)logarithmicbinary search
O(n)linearlinear search
O(n log n)linearithmicmerge sort, quicksort (average)
O(nยฒ)polynomialbubble sort, insertion sort
O(2โฟ)exponentialbrute-force subsets

Space complexity is measured the same way. Bubble and insertion sort are O(1) space โ€” they sort in place. Merge sort is O(n) space, because merging needs a temporary array. You are always trading time against space.

Read it properly: O(nยฒ) is an upper bound on the worst case. Doubling n makes an O(nยฒ) algorithm take four times as long, but an O(log n) algorithm take just one more step. That is the whole reason complexity is worth studying.

2.3 ยท Searching

Linear, binary and binary tree search

Linear search โ€” check each element in turn. Works on any list, sorted or not. Worst case O(n).

Binary search โ€” requires a sorted list. Check the middle; discard the half that cannot contain the target; repeat. Each comparison halves the search space, so it is O(log n).

low โ† 0 : high โ† n-1 WHILE low <= high mid โ† (low + high) DIV 2 IF a[mid] = target THEN RETURN mid ELSE IF a[mid] < target THEN low โ† mid + 1 ELSE high โ† mid - 1 ENDWHILE RETURN -1

Binary tree search โ€” the same halving idea on a BST: go left if smaller, right if larger. O(log n) on a balanced tree โ€” but if the data was inserted already sorted, the tree degenerates into a chain and it collapses to O(n).

The catch: binary search needs sorted data, and sorting costs O(n log n). Sort once and search a million times, and it is a huge win. Sort in order to perform a single search, and you have wasted your time โ€” use linear search.

Calculate

Your turn โ€” binary search

1What is the maximum number of comparisons a binary search needs on a sorted list of 64 items?
comparisons
Hint: Each comparison halves the list: 64 โ†’ 32 โ†’ 16 โ†’ 8 โ†’ 4 โ†’ 2 โ†’ 1. Count the halvings.
2.3 ยท Sorting

Bubble, insertion, merge and quicksort

SortBestWorstSpace
BubbleO(n) with a swap flagO(nยฒ)O(1)
InsertionO(n) if nearly sortedO(nยฒ)O(1)
MergeO(n log n)O(n log n)O(n)
QuickO(n log n)O(nยฒ)O(log n)

Bubble โ€” compare adjacent pairs and swap; after each pass the largest item has bubbled to the end. Total comparisons in the worst case = n(nโˆ’1)/2.

Insertion โ€” take each item and insert it into its correct place among those already sorted, shuffling the larger ones along. Excellent on nearly sorted data; it is what people actually do with a hand of cards.

Merge โ€” divide and conquer: split in half, sort each half recursively, then merge the sorted halves. There are logโ‚‚ n levels, each merging n items, so it is O(n log n) in every case.

Quicksort โ€” choose a pivot, partition the list into items smaller and larger than it, and recurse on each partition. Fast in practice, and sorts nearly in place.

Quicksort's worst case: if the pivot is always the smallest or largest item โ€” which happens if you take the first element of an already sorted list โ€” each partition removes only one element, giving n levels of recursion and O(nยฒ). Choosing a random or median pivot makes that vanishingly unlikely, which is why real implementations do exactly that.

Calculate

Your turn โ€” insertion sort

2How many comparisons does insertion sort make in the worst case (a list in reverse order) on 6 items?
comparisons
Hint: The second item is compared with 1 item, the third with 2, and so on up to the sixth. Add them up: 1 + 2 + 3 + 4 + 5.
Quick check

Sorting

?Which statement about merge sort is correct?
2.3 ยท Traversal

Breadth-first and depth-first search

Breadth-first (BFS)Depth-first (DFS)
Uses a queue (FIFO)Uses a stack (LIFO), or recursion
Visits all neighbours first, expanding in ringsPlunges as deep as possible, then backtracks
Finds the shortest path in an unweighted graphMaze solving, topological sort, cycle detection
Memory grows with the whole frontierMemory proportional to the depth

Both visit every reachable vertex once, both keep a visited set, and both are O(V + E) with an adjacency list.

The trap: BFS finds the route with the fewest edges, not the lowest cost. On a weighted graph the fewest-edges route can easily be the most expensive one โ€” which is exactly why Dijkstra's algorithm exists.

2.3 ยท Path finding

Dijkstra and A*

Dijkstra finds the shortest path from a source to every other vertex in a graph with non-negative weights:

  • set the source distance to 0 and all others to โˆž;
  • take the unvisited vertex with the smallest distance;
  • relax its edges: if distance(current) + weight < distance(neighbour), update the neighbour and record its predecessor;
  • mark the current vertex visited โ€” its distance is now final โ€” and repeat.

It fails on negative weights, because it finalises each vertex on the assumption that no cheaper route can appear later โ€” an assumption a negative edge destroys.

A* is Dijkstra plus a heuristic. Each vertex is scored:

f(n) = g(n) + h(n)g = the actual cost from the start ยท h = the estimated cost to the goal

By expanding the lowest f first, A* is steered towards the goal and explores far fewer vertices than Dijkstra. If the heuristic never overestimates (it is admissible โ€” straight-line distance is the classic choice), A* is guaranteed to find the shortest path.

Set h(n) = 0 and A* becomes Dijkstra exactly. The heuristic is the entire difference: it is informed guidance about which direction is worth exploring, and it is why every satnav uses A*, not Dijkstra.

Calculate

Your turn โ€” Dijkstra

3Run Dijkstra from A on this weighted, undirected graph. What is the length of the shortest path from A to E?
EdgeWeightEdgeWeight
A โ€“ B3C โ€“ D4
A โ€“ C6C โ€“ E7
B โ€“ C2D โ€“ E2
B โ€“ D9
Hint: Is Aโ†’C direct (6) really the cheapest way to C, or is Aโ†’Bโ†’C? Settle C first, then D, then E. Compare reaching E via C with reaching it via D.
Calculate

Your turn โ€” A*

4In an A* search, a node has an actual cost from the start of g = 7 and an estimated remaining cost of h = 5. What is its f score?
Hint: f(n) = g(n) + h(n).
Quick check

A*

?What does A* add to Dijkstra's algorithm, and why does it help?
Quick check

Traversal

?A robot must find the route through an unweighted grid maze using the fewest moves. Which traversal guarantees it?
Sort it

Sort by complexity

Tap an algorithm or operation, then tap its complexity.

๐Ÿชถ O(log n)

โž– O(n)

๐Ÿข O(nยฒ)

Match it

Match the algorithm

Tap an item on the left, then its partner on the right.

Description
Algorithm
Recap

The big ideas to know

Big-O: O(1) ยท O(log n) ยท O(n) ยท O(n log n) ยท O(nยฒ) ยท O(2โฟ) โ€” measure space as well as time

Searching: linear O(n) on any data ยท binary O(log n) needs sorted data ยท BST O(log n) balanced, O(n) degenerate

Sorting: bubble & insertion O(nยฒ) in place ยท merge O(n log n) always but O(n) space ยท quicksort O(n log n) average, O(nยฒ) with a bad pivot

Traversal: BFS = queue = fewest edges ยท DFS = stack = deep then backtrack ยท both O(V + E)

Path finding: Dijkstra relaxes from the closest unvisited vertex (no negative weights) ยท A*: f = g + h, admissible h guarantees optimality

That is the whole of OCR 2.3. Press Finish to see your score.

๐Ÿ†

Mini-lesson complete!

โญโญโญ

You've worked through Algorithms for OCR A-level Computer Science (H446). ๐ŸŽ‰

Your stars: 0 / 0

Next: test yourself in the Evaluate stage Confidence Quiz, then lock it in with Verify.

๐Ÿ“ฃ Smashed it? Share your score

Challenge a mate to beat your stars, or show a parent how you got on.

โ†’ Back to all subjects