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

Free lesson

2.11 (4 of 4): Comparing algorithms

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

50 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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 you also count the work. 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

You 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))

Make a free account to save your work and track your progress.

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.

You 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

One pair fewer each pass

The code below checks one pair fewer each pass than the bubble sort lesson's code, because the biggest items are already at the end.

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]))

Make a free account to save your work and track your progress.

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.

What happens when the list grows?

Important

Bubble sort and insertion sort do far more work as the list gets bigger. Merge sort grows much more slowly. That is why it wins on big lists.

Extra: How the work grows, in numbers

ItemsLinear searchBinary searchBubble or insertion sortMerge sort
1010445About 25
10010074950About 570
1000100010About 500 000About 9000

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

Match the job to the best algorithm

Have a go

Loading…

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

Watch: count the work

Press Play on the short film below. It counts the work of a linear search and a bubble sort on different lists. Watch how the count changes with the data, and which sort wins as the list grows.

Film: comparing algorithms

Comparing algorithms

Every scene, as text

  1. Count the work, not the time. You can compare algorithms by memory space, execution time or the number of comparisons. Timing is not a fair test, because a fast computer makes a slow method look good. The lesson's linear search adds 1 to comparisons for each item it checks (ringed) and stops when it finds the target, so its count is the same on every computer.
  2. Myth (false): an algorithm always does the same amount of work. The same linear search on the numbers 1 to 100: target 1, the first item, makes 1 comparison, the best case; target 100, the last, makes 100, the worst case; 500, not in the list, also makes 100; 50, halfway, makes 50, about the average case.
  3. The cure: ask which data means the least work and which the most. The lesson's bubble sort makes 9 comparisons on [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], already sorted, the best case: the first pass makes no swaps, so it stops. On [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], in reverse order, the worst case, it makes 45: each pass checks one pair fewer (the line pairs = pairs - 1, ringed), because the biggest items are already at the end, so 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 45.
  4. The lesson's table of three sorts on 10 items: bubble sort and insertion sort both make 9 comparisons when the list is already sorted and 45 when it is in reverse order, with almost no extra memory; merge sort makes about 15 to 25, but it needs extra memory, because a whole new list is made at each merge.
  5. How the work grows, worst case: 10, 100 and 1000 items take bubble or insertion sort 45, 4950 and about 500 000 comparisons, and merge sort about 25, about 570 and about 9000. 10 times the items gives bubble or insertion sort about 100 times the work, but merge sort under 25 times, not 100 times, so merge sort wins on big lists; for a short list a simple sort is enough.

Quick check: cases and choices

Have a go

Quick check: cases and choices

5 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

Questions to ask when you choose

QuestionIf the answer is yes
Is the list already sorted?Binary search is possible. Insertion sort is quick
Is the list big?Merge sort and binary search pay off
Will you search many times?Sort once, then use binary search
Is memory very short?Avoid merge sort. Use insertion or bubble sort
Is the list short or the job a one-off?The simple algorithm is fine

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

Your turn: count the work

Count the work of linear search and binary search. The tests need an exact count, so follow these rules.

  1. count_linear(items, target) counts the items compared with the target before the search stops.
  2. count_binary(items, target) counts the middle items looked at, with the middle index (low + high) // 2. Each middle item counts as 1, even if you test it with both == and <.
  3. best_case_target(items) gives back the item a linear search finds with the fewest comparisons.
  4. worst_case_target(items) gives back the item it finds with the most.

Press Run Tests to check.

Code: python
def count_linear(items, target):
    # Linear search. Count how many items are compared with the target.
    # Stop as soon as the target is found. If it is not there, you compare every item.
    return None


def count_binary(items, target):
    # Binary search on a sorted list. Count how many middle items are compared with the target.
    # Use middle = (low + high) // 2 each time, like in the lesson.
    return None


def best_case_target(items):
    # Give back the item that a linear search finds with the fewest comparisons.
    return None


def worst_case_target(items):
    # Give back the item that a linear search finds with the most comparisons.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

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

Exit quiz

Have a go

Exit quiz

5 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

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.