Programming
How to choose an algorithm, prove it correct and argue its cost
Computer Science | Undergraduate (Level 5) | December 2026
WHAT IS INSIDE
1. Measuring cost and arguing correctness
2. Sorting, selection and hashing
3. Graphs: traversal, shortest paths and spanning trees
4. Greedy, divide and conquer, dynamic programming
Exam question patterns
Glossary of exam-ready definitions
1. Measuring cost and arguing correctness
Asymptotic notation describes growth, not seconds. O gives an upper bound, Omega a lower bound and
Theta a tight bound, so saying an algorithm is O(n^2) leaves open that it may be Theta(n). Worst case,
average case and space are three separate answers, and an algorithm with a good average and a bad worst
case is unsuitable wherever an adversary controls the input. Recurrences are solved by substitution, by the
recursion tree, or by the master theorem, whose three cases compare the work at the root with the work at
the leaves.
Correctness is argued with an invariant: a property true before the first iteration, preserved by each
iteration and sufficient at termination. Loop invariants prove iterative algorithms, induction proves
recursive ones, and an exchange argument proves greedy algorithms by showing that swapping any
solution towards the greedy choice never worsens it. A lower bound such as the n log n
comparison-sorting bound explains why a faster comparison sort cannot exist, which is a different claim
from failing to find one.
• Bound vs tight bound - O is not Theta; state which one you mean.
• Average is not worst - quicksort is Theta(n log n) average and Theta(n^2) worst.
• Space counts - merge sort needs Theta(n) auxiliaries, heapsort O(1).
• Lower bound - comparison sorting needs Omega(n log n); say so when asked for optimality.
2. Sorting, selection and hashing
Merge sort divides, sorts and merges in Theta(n log n) time with Theta(n) extra space and is stable;
quicksort partitions in place, is usually faster in practice and degrades to Theta(n^2) on already-sorted
input unless the pivot is randomised or chosen by median-of-three. Heapsort builds a heap in linear time
and repeatedly extracts the maximum, giving Theta(n log n) worst case with O(1) space but no stability.
Counting and radix sort break the comparison bound by assuming a bounded key range, which is the
assumption to state explicitly.
Selection asks for the k-th smallest element: sorting answers it in Theta(n log n), a heap in Theta(n + k log
n), and quickselect in Theta(n) average with Theta(n^2) worst. Hash tables give O(1) average lookup
under a good hash and load factor, degrade to Theta(n) with clustering, and must handle collisions by
chaining or open addressing. When an exam asks for the right structure, the load factor and the worst case
are usually the discriminating marks.
Algorithms: Sorting, Graphs, Greedy and Dynamic Programming Page 1 of 3