Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

Comparing algorithms

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

50 minutes

Which taxi is quicker?

Two taxi companies say they are the quickest. How can you decide? You could time them. But one runs on a busy day and one on a quiet day. The test is not fair.

It is the same for the methods a program uses. A fast computer makes a slow method look good. So we also count the work, and the count is the same on every computer.

Key words

WordWhat it means
MetricA measure you use to compare things.
Execution timeHow long the algorithm takes to run.
Memory spaceHow much memory the algorithm needs.
ComparisonsHow many times two values are checked against each other.
Best caseThe situation where the algorithm does the least work.
Worst caseThe situation where the algorithm does the most work.
Average caseA typical situation, somewhere between the best and the worst.
AlgorithmA set of steps to solve a problem.
Linear searchLook at each item in turn from the start.
Binary searchLook at the middle of a sorted list and keep one half.
Bubble sortSwap neighbours that are in the wrong order, pass after pass.
Insertion sortSlide each item into its place in the sorted part.
Merge sortSplit the list, sort the parts, then merge them.

The cells students fill in are left blank in this preview.

Three ways to measure

We compare algorithms with three metrics.

Memory space: how much extra memory it needs. Execution time: how long it takes. Number of comparisons: how many checks it makes. This is the fairest, because it does not depend on how fast the computer is.

Try it: count the checks

Code: python
def linear_comparisons(items, target):
    comparisons = 0
    for item in items:
        comparisons = comparisons + 1
        if item == target:
            return comparisons
    return comparisons

numbers = []
for n in range(1, 101):
    numbers.append(n)

print("Best case:", linear_comparisons(numbers, 1))
print("Worst case:", linear_comparisons(numbers, 100))
print("Not in the list:", linear_comparisons(numbers, 500))
print("Somewhere in the middle:", linear_comparisons(numbers, 50))

Worked example: searching 100 items

AlgorithmBest caseWorst caseAverage case
Linear search1 check: the target is first100 checks: the target is last or missingAbout 50 checks: half the list
Binary search1 check: the target is in the middle7 checksAbout 6 checks: near the worst case

The cells students fill in are left blank in this preview.

Best, worst and average case

The same algorithm can be quick or slow, depending on the data. The best case is the lucky data. The worst case is the unlucky data. The average case is what you expect most days.

We do not need maths to find them. Ask: what data would make this algorithm do the least work? What data would make it do the most?

Quick check: name the case

Have a go

Quick check: name the case

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Try it: count the sort

Code: python
def bubble_comparisons(items):
    numbers = items
    comparisons = 0
    pairs = len(numbers) - 1
    swapped = True
    while swapped and pairs > 0:
        swapped = False
        for i in range(pairs):
            comparisons = comparisons + 1
            if numbers[i] > numbers[i + 1]:
                temp = numbers[i]
                numbers[i] = numbers[i + 1]
                numbers[i + 1] = temp
                swapped = True
        pairs = pairs - 1
    return comparisons

print("Already sorted:", bubble_comparisons([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print("Reversed:", bubble_comparisons([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]))

The cases for sorting 10 items

AlgorithmBest caseWorst caseExtra memory
Bubble sort9 comparisons: already sorted45 comparisons: in reverse orderAlmost none
Insertion sort9 comparisons: already sorted45 comparisons: in reverse orderAlmost none
Merge sortAbout 15 comparisonsAbout 25 comparisonsA whole new list is made at each merge

The cells students fill in are left blank in this preview.

The lesson goes on

8 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.