Computer ScienceCore22 min read

Algorithms & Big-O

Sorting, searching, and measuring cost honestly

This topic appears in:

01

Big-O is about growth, not speed

Big-O does not tell you how many seconds your code takes. It tells you how the cost grows when the input grows. That is the durable question, because hardware gets faster every year but n² stays n².

This is why constants get dropped. An algorithm doing 3n + 200 steps is written O(n): as n heads for a million, the 3 and the 200 stop mattering, and the shape of the curve is all that survives.

Push n to 120 and switch the y-axis to log. The gap between O(n log n) and O(n²) is what separates a sort that finishes and a sort that hangs.

02

The numbers that make it real

At n = 1,000,000, assuming a billion operations per second:

ComplexityOperationsRough time
O(log n)20instant
O(n)1,000,0001 millisecond
O(n log n)20,000,00020 milliseconds
O(n²)10¹²~17 minutes
O(2ⁿ)10³⁰¹⁰³⁰longer than the universe has existed

This is why the choice matters

Between O(n log n) and O(n²) there is no clever optimisation, no faster laptop, and no compiler flag that closes the gap. At scale you must change the algorithm.

03

Sorting, watched step by step

Bubble sort repeatedly swaps neighbours that are out of order. Simple, and O(n²) — genuinely useless beyond teaching.

Insertion sort builds a sorted region on the left, sliding each new element back into place. Also O(n²), but it is O(n) on nearly-sorted data, which makes it excellent for small or almost-ordered inputs.

Selection sort finds the minimum and swaps it into place. Always O(n²) comparisons, but only n−1 swaps — useful when writing is expensive.

Quicksort picks a pivot, partitions everything around it, and recurses. O(n log n) on average and the fastest in practice, though a bad pivot on already-sorted data degrades it to O(n²).

Run Bubble, then Quick on the same shuffle. Compare the comparison counters at the end — that number is Big-O made concrete.

04

Binary search: the log in O(log n)

Searching a sorted array by halving is the cleanest O(log n) there is. Check the middle. Too big? Throw away the top half. Too small? Throw away the bottom. Each step deletes half the remaining possibilities.

Starting from a million items: 500,000 → 250,000 → 125,000 → … → 1. Twenty steps. Doubling the data adds exactly one step, which is what logarithmic growth means.

steps ≈ log₂(n)n = 1,000,000 → ~20 stepsthe array must already be sorted
05

What makes something an algorithm

Before analysing efficiency, be precise about what is being analysed. An algorithm is a finite sequence of unambiguous steps that takes defined inputs and produces defined outputs. All four conditions are examinable.

Finite — it must terminate. Unambiguous — every step has exactly one interpretation. Defined inputs and outputs — you know what it needs and what it produces. Effective — every step is something that can actually be carried out.

Written asStrengthWeakness
Flowchartthe flow of control is visible at a glanceunwieldy beyond about twenty steps
Pseudocodeclose to real code, scales to long algorithmsno visual sense of the structure
Structured Englishreadable by a non-programmereasy to leave ambiguous
Actual codeunambiguous and runnableties the idea to one language

Correctness and efficiency are separate questions

An algorithm can be correct and unusably slow, or fast and wrong. Establish correctness first — trace it by hand on a small input and check the answer — and only then ask about efficiency. Optimising an algorithm that produces the wrong answer is the most reliable way to waste an afternoon.

06

Searching: linear against binary

A linear search examines each item in turn until it finds the target or runs out. It works on any list in any order, and on average examines half of it — O(n).

A binary search requires the list to be sorted. It looks at the middle item, and since the list is ordered it can discard half the remaining items at every step — O(log n). For a million items, linear search averages 500 000 comparisons and binary search needs at most 20.

The catch is the precondition. Sorting an unsorted list to permit one binary search costs more than simply searching it linearly. Binary search pays off when the same list is searched many times.

Worked example

A list of 1000 sorted names is searched. How many comparisons does binary search need in the worst case, and why?

  1. Each comparison discards half of the remaining items.The list is sorted, so knowing the target is smaller than the middle item rules out the entire upper half at once.
  2. After each step the remaining size is 1000, 500, 250, 125, 63, 32, 16, 8, 4, 2, 1.Halving repeatedly, rounding up.
  3. That is 10 steps, and 2¹⁰ = 1024, just over 1000.The worst case is the smallest power of 2 that reaches the list size.
  4. So at most 10 comparisons, against an average of 500 for a linear search.Doubling the list to 2000 adds one comparison, not a thousand — which is what O(log n) means in practice.

10 comparisons, because 2¹⁰ = 1024 ≥ 1000.

07

Comparing two algorithms fairly

Timing a program with a stopwatch measures the machine, the language and the compiler as much as the algorithm. A fast computer running a poor algorithm beats a slow computer running a good one — right up to the point where the input grows, and then it does not.

So algorithms are compared by counting the operations they perform as a function of the input size n, and reporting only how that count grows. Constants and lower-order terms are dropped, because for large n they stop mattering: 3n² + 50n + 900 is O(n²), since the n² term eventually dominates everything else however large the other numbers look.

CaseMeansExample: linear search
Best casethe most favourable inputtarget is the first item — 1 comparison
Average casetypical inputtarget is halfway — n/2 comparisons
Worst casethe least favourable inputtarget is last or absent — n comparisons
Space complexityextra memory neededO(1) — no extra storage per item

Why the worst case is usually the one quoted

An average depends on assumptions about the input that may not hold, and a best case tells you almost nothing. The worst case is a guarantee: whatever the input, it will not be slower than this. For anything that must respond within a time limit, a guarantee is the only figure worth having — which is why O-notation normally describes the worst case unless the question says otherwise.

Practice questions

6 questions · 27 marks · full working on every one

Try each one on paper first, then open the working. The marks are shown where they are actually awarded, because that is where they are actually lost.

Short questions

3 · 7 marks

Two marks each, in the style of the short-question section of the paper. Answer in two or three lines.

SQ1[2 marks]
State one condition that must be met before a binary search can be used, and state why.
Model answer

The data must already be sorted. The algorithm discards half the list at each step by comparing with the middle item, which is only valid if the order is known.

Examiner tip. The condition alone is one mark; the reason is the second.

SQ2[2 marks]
Explain what is meant by the time complexity of an algorithm.
Model answer

A measure of how the number of operations grows as the size of the input grows, written in big-O notation. It describes the trend, not the exact running time on a particular machine.

Examiner tip. Mentioning that it is machine-independent is often the second mark.

SQ3[3 marks]
A linear search of 1000 items takes at most 1000 comparisons. State the maximum number a binary search would need, and explain.
Model answer

About 10, because 2¹⁰ = 1024. Each comparison halves the remaining list, so the maximum is log₂ n rounded up.

Examiner tip. Show the power of two. "Because it is faster" scores nothing.

Long questions

2 · 15 marks

Theory and numerical together, as they appear in the long-question section.

LQ1[7 marks]
A bubble sort is used on the list 5, 3, 8, 1.
  1. Write out the list after each complete pass. [3]
  2. State the total number of passes needed and explain how the algorithm knows it has finished. [2]
  3. State the time complexity of a bubble sort and explain why it is unsuitable for large data sets. [2]
Mark scheme
  1. After pass 1: 3, 5, 1, 8[1]
  2. After pass 2: 3, 1, 5, 8[1]
  3. After pass 3: 1, 3, 5, 8[1]
  4. Three passes; a fourth confirms no swaps[1]
  5. A flag records whether any swap was made; if a whole pass makes none, the list is sorted[1]
  6. O(n²)[1]
  7. Doubling the data quadruples the work, so it becomes impractically slow[1]

Examiner tip. Write the list after each pass, not after each swap. The question asks for passes and a swap-by-swap list will not match the mark scheme.

LQ2[8 marks]
A program must find whether a student name appears in a sorted list of 5000 names.
  1. Write pseudocode for a binary search on this list. [5]
  2. Explain what your code returns when the name is not present. [1]
  3. Compare the number of comparisons with a linear search on the same list. [2]
Mark scheme
  1. Initialises low = 1 and high = 5000[1]
  2. Loops while low <= high[1]
  3. Calculates mid = (low + high) DIV 2[1]
  4. Compares and returns mid if the name matches[1]
  5. Otherwise sets high = mid − 1 or low = mid + 1 correctly[1]
  6. Returns a value such as −1 or FALSE once low > high[1]
  7. Binary search: at most 13 comparisons, since 2¹³ = 8192[1]
  8. Linear search: up to 5000, so binary search is dramatically faster[1]

Examiner tip. The loop condition low <= high, not low < high. With the strict version a list of one item is never checked and single-element searches fail.

Exam questions

1 · 5 marks

Multi-part questions with a full mark scheme.

Q1[5 marks]
An algorithm is described as having complexity O(n log n).
  1. Name one sorting algorithm with this complexity. [1]
  2. Explain why it scales better than O(n²) as n grows. [2]
  3. A data set of 1000 items takes 2 seconds with the O(n log n) algorithm. Estimate the time for 2000 items and justify your estimate. [2]
Mark scheme
  1. Merge sort or quicksort (average case)[1]
  2. The log n factor grows very slowly compared with the extra factor of n[1]
  3. So the gap between the two widens rapidly as n increases[1]
  4. Doubling n slightly more than doubles n log n[1]
  5. So roughly 4.2 to 4.5 seconds, a little over doubleaccept "just over 4 seconds" with reasoning[1]

Examiner tip. For O(n²) doubling the data would give 8 seconds. Quoting that contrast makes the justification in part (c) obvious.