CIE AS & A Level Computer Science, section 19.1 (Algorithms)
Why compare algorithms
Different algorithms solve the same problem with different time (number of steps) and space (memory). Big O notation describes how these grow as the input size increases, ignoring constants and smaller terms. It gives the worst case (an upper limit).
Common orders
| Big O | Name | Example | Time for (steps, roughly) |
|---|---|---|---|
| constant | reading an array element | 1 | |
| logarithmic | binary search | 10 | |
| linear | linear search | 1 000 | |
| linearithmic | merge sort | 10 000 | |
| polynomial | bubble sort, insertion sort | 1 000 000 | |
| exponential | trying every subset | far too large |
Working it out
- A single loop over items is .
- A loop inside a loop, both over items, is .
- A loop that halves the data each time is .
- Ignore constants: is . Keep only the biggest term: is .
def first_item(items): # O(1)
return items[0]
def total(items): # O(n)
t = 0
for x in items:
t += x
return t
def has_pair(items): # O(n^2)
for a in items:
for b in items:
if a + b == 10:
return True
return False
Space complexity
Space also grows with . An algorithm that makes a copy of the list needs extra space; one that sorts in place needs .
Doubling the input
| Order | Effect of doubling |
|---|---|
| time doubles | |
| time becomes four times | |
| one extra step |
Common mistake: including constants or smaller terms, such as writing . Write . Also, Big O describes how the time grows, not the exact time in seconds.
Exam tip: to find the order, look at the loops and the biggest term. Say what happens to the time when the input doubles, to show you understand the growth.
Check yourself
What is the Big O of a loop inside another loop, each running times?
.
Simplify .
.
What happens to the time of an algorithm if the input size doubles?
It becomes four times as long.