OCR H446, section 2.3.1 (c)
How do you say that one algorithm is better than another? Timing it on one computer isn't reliable, because the result depends on the hardware, the language and what else is running. Instead we measure how the amount of work grows as the size of the input grows.
Measures of efficiency
| Measure | What it describes |
|---|---|
| Time complexity | How the number of steps grows with the input size |
| Space complexity | How the memory used grows with |
For time, we count the basic operations (comparisons, assignments, arithmetic), not seconds.
Counting steps
def total(items):
s = 0 # 1 step
for x in items: # n times
s = s + x # 1 step each time
return s # 1 step
The number of steps is about . As gets large, the term dominates, so we say the time grows in proportion to .
Big O notation
Big O notation describes how the running time (or space) grows as the input size grows, ignoring constants and smaller terms. It gives an upper bound on the growth, usually for the worst case.
Rules for finding it:
- Drop constants: becomes .
- Keep only the largest term: becomes .
So is .
The common classes
| Notation | Name | Example | Effect of doubling |
|---|---|---|---|
| Constant | Getting items[5]; push onto a stack |
No change | |
| Logarithmic | Binary search | Adds one step | |
| Linear | Linear search; summing a list | Doubles | |
| Linearithmic | Merge sort, quick sort (average) | A little more than doubles | |
| Polynomial (quadratic) | Bubble sort; a loop inside a loop | Four times | |
| Polynomial | nested loops | times | |
| Exponential | Trying every subset; naive recursive Fibonacci | Squares the time | |
| Factorial | Trying every order (travelling salesman) | Explodes |
How fast they grow
| 10 | 3 | 10 | 33 | 100 | 1,024 |
| 100 | 7 | 100 | 664 | 10,000 | |
| 1,000 | 10 | 1,000 | 9,966 | 1,000,000 | far too big |
Order from best to worst: .
Exponential problems are intractable for even moderate (2.2.2 (a)).
Recognising complexity in code
Constant:
first = items[0] # one step, however long the list
Linear:
A single loop over the data:
for x in items:
print(x)
Quadratic:
A loop inside a loop, both over the data:
for a in items:
for b in items:
print(a, b) # runs n * n times
Logarithmic:
The problem is halved each time:
n = 1000
steps = 0
while n > 1:
n = n // 2
steps = steps + 1 # about 10 steps
Exponential:
Each call makes two more calls, with only a small reduction in size:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Best, average and worst case
| Case | Meaning | Linear search |
|---|---|---|
| Best | The fewest steps | Item is first: |
| Average | Typical | About : |
| Worst | The most steps | Item is last or missing: |
Big O is normally quoted for the worst case, which is a guarantee.
Space complexity
The same idea applies to memory.
| Algorithm | Extra space |
|---|---|
| Bubble sort, insertion sort (in place) | |
| Merge sort (copies while merging) | |
| Recursion to depth | (stack frames) |
| Memoisation (storing results) |
Ways of finding efficiency
- Count the operations for different input sizes, and look at the pattern.
- Analyse the structure of the code (loops, nested loops, halving, recursion).
- Measure the run time with a timer on different sizes (a rough check, and affected by the machine).
- Compare the growth: when doubles, does the time double, quadruple, or hardly change?
import time
for n in [1000, 2000, 4000]:
data = list(range(n))
start = time.perf_counter()
for a in data:
for b in data:
pass
print(n, time.perf_counter() - start) # ~4x per doubling
Worked example
Task: state the time complexity of each piece of code.
# A
total = 0
for x in items:
total += x
# B
for i in range(len(items)):
for j in range(len(items) - 1 - i):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
# C
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
break
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
- A: . One loop, and each pass takes one step.
- B: . It's a bubble sort: nested loops, with the inner loop running about times for each of passes, which gives about comparisons. Drop the constant .
- C: . It's a binary search: the range is halved each pass, so for 1,000 items there are about 10 passes.
Exam tip: to find Big O from code, look at the loops: one loop is , nested loops are , halving is , no loop is . Drop constants and lower terms. Always say which case (usually the worst) you mean. You may be asked to order complexities, so learn the order.
Check yourself
Why is Big O used instead of timing the program?
Run time depends on the hardware, language and other programs running. Big O describes how the work grows with input size, so it is the same for any machine.
What is the Big O of: 3n² + 5n + 2?
O(n²). Drop the constants and keep only the largest term.
Give the Big O of a linear search, a binary search and a bubble sort
Linear search O(n); binary search O(log n); bubble sort O(n²).
Put these in order from fastest-growing to slowest-growing: O(n), O(2ⁿ), O(1), O(n²), O(log n)
O(2ⁿ), O(n²), O(n), O(log n), O(1).
What happens to the time of an O(n²) algorithm when the input size doubles?
It increases by about four times.