← GCSE Computer Science · OCR · GCSE Computer Science revision
⭐ 0
OCR GCSE Computer Science (J277) · 2.1 Algorithms
Mini-Lesson

Algorithms

5 missions. Guess, learn, then check. Your place is saved.

  1. Mission 1Why does the Tube map ignore real distances, yet still work?
  2. Mission 2How can you find a bug without running the program?
  3. Mission 3How can 20 checks find one name among a million?
  4. Mission 4Why is it called a bubble sort?
  5. Mission 5Why does a fast sort start by chopping a list into pieces?
Mission 1

Why does the Tube map ignore real distances, yet still work?

Make a guess: Why does the Tube map ignore real distances, yet still work?

Algorithms · computational thinking

Breaking a problem down

Decomposing a problemPlan a Tube journeyFind neareststationChoose therouteWork outjourney timePick the linesFind where tochange
  • Decomposition means breaking a problem into smaller sub-problems, each doing one identifiable task.
  • Each sub-problem can be broken down again until it is simple to solve.
  • Parts can be solved and tested separately, even by different people.
  • "Plan a Tube journey" splits into: find the nearest station, choose the route, work out the time.
Algorithms · computational thinking

Leaving detail out

Abstraction: two mapsGeographic: real shapes and distancesAsh ParkBell StreetCole CrossDene RoadElm HillFox LaneGate Way1 kmBeck-style: straight lines, equal gapsAsh ParkBell StreetCole CrossDene RoadElm HillFox LaneGate WaySame stations, same order, same connections.
  • Abstraction is removing unnecessary detail from a problem to focus on what matters.
  • Harry Beck's 1933 Tube map keeps the lines, the order of stations and where they connect.
  • It drops true distances and the real shape of the tunnels: travellers do not need them.
  • A program does the same: it models the real world with only the details the task needs.
Quick check
?A program models a snooker shot to predict where the balls will stop. Which detail should abstraction remove?
Algorithms · computational thinking

Inputs, processes and outputs

Input, process, outputInputHours wantedCoinsProcessWork out costWork outchangeOutputTicketChange
  • To analyse a problem, identify its inputs (data going in), processes (what is done to the data) and outputs (results).
  • Car park ticket machine: inputs are the hours wanted and the coins; the process works out the cost and change; outputs are the ticket and the change.
Quick check
?A program asks for a room's length and width and the carpet price per m², then shows the total cost. Which of these is a process?
Algorithms · computational thinking

Structure diagrams

Structure diagramQuiz gameSet upPlay a roundEnd gameLoadquestionsSet score to0AskquestionCheckanswerUpdatescoreShow finalscore
  • A structure diagram shows how a problem is decomposed, from the top down.
  • The top box is the whole problem. Each level below splits a box into its sub-problems.
  • Lines link each box to the sub-problems it is made of.
  • Boxes at the bottom are small enough to become a subroutine or a few lines of code.
Algorithms · computational thinking

Algorithms and algorithmic thinking

  • An algorithm is a sequence of steps that can be followed to complete a task.
  • The same algorithm can be written as a flowchart, as pseudocode or as program code.
  • Algorithmic thinking is working out the steps that solve a problem, and their order, so the solution can be reused for similar problems.
  • Decomposition, abstraction and algorithms together are the core of computational thinking.
Quick check
?A team splits a school app into login, timetable and messages, and gives each part to a different programmer. Which idea is this?
Mission check

?Why does the Tube map ignore real distances, yet still work?
Mission 2

How can you find a bug without running the program?

Make a guess: How can you find a bug without running the program?

Algorithms · representing algorithms

Flowchart symbols

Flowchart symbolsTerminatorInput/outputProcessYesNoDecisionSubroutineFlow line
SymbolMeaning
Rounded rectangle (terminator)Start or Stop
ParallelogramInput or output
RectangleProcess, such as a calculation
DiamondDecision: two exits, Yes/No or True/False
Rectangle with double sidesSubroutine (a separate sub-program)
Arrow (flow line)The direction control flows
  • A flowchart shows an algorithm's steps and the order they happen in.
Quick check
?This flowchart is run with the input 10. What does it output?
Hot, cold or mildYesNoYesNoStartINPUT temptemp > 30?OUTPUT 'Hot'temp < 10?OUTPUT 'Cold'OUTPUT 'Mild'Stop
Algorithms · representing algorithms

Pseudocode and code

  • Pseudocode writes an algorithm as structured statements, not tied to one programming language.
  • OCR exam questions use the OCR Exam Reference Language shown here
  • This algorithm loops while the count is above 0. Each time round it doubles the result and counts down by 1.
OCR Exam Reference Language
count = 3
result = 1
while count > 0
    result = result * 2
    count = count - 1
endwhile
print(result)
Algorithms · representing algorithms

Trace tables

Trace tablecountresultOutput312214088
  • A dry run follows an algorithm by hand. A trace table records it: one column per variable, plus Output.
  • Add a row when a value changes. For screen 3, count goes 3, 2, 1, 0 and result goes 1, 2, 4, 8.
  • The pattern shows the purpose: it works out 2 to the power of the starting count.
Calculate
?Dry-run this algorithm. What does it output?
OCR Exam Reference Language
num = 37
steps = 0
while num > 1
    num = num DIV 2
    steps = steps + 1
endwhile
print(steps)
Algorithms · representing algorithms

Errors in algorithms

  • A syntax error breaks the language's rules, e.g. a missing endif. The code will not run.
  • A logic error: the code runs but gives a wrong result, e.g. > where ≥ was needed.
  • To fix a logic error, dry-run with test data, find where the trace goes wrong, correct it and retest.
Quick check
?This algorithm should output Pass for any mark of 50 or more. Which test mark shows that it has a logic error?
OCR Exam Reference Language
mark = int(input("Enter mark"))
if mark > 50 then
    print("Pass")
else
    print("Fail")
endif
Mission check

?How can you find a bug without running the program?
Mission 3

How can 20 checks find one name among a million?

Make a guess: How can 20 checks find one name among a million?

Algorithms · searching

Linear search

Linear search for 1527018126323153444435706indexcheckfound 15never checked
  • A linear search checks each item in turn, from the first, until it finds the target or reaches the end.
  • The list can be in any order.
  • Finding 15 in [27, 8, 63, 15, 44, 3, 70] takes 4 checks.
  • At worst (target last, or missing) it checks every item.
OCR Exam Reference Language
found = False
i = 0
while i < 7 AND found == False    // items holds 7 values: index 0 to 6
    if items[i] == target then
        found = True
    else
        i = i + 1
    endif
endwhile
if found == True then
    print(i)
else
    print("Not found")
endif
Calculate
?A linear search looks for 50 in [27, 8, 63, 15, 44, 3, 70]. How many items does it check?
Algorithms · searching

Binary search

Binary search for 58012345678910111213143811151924273136404452586370firstmidlast58 > 31: discard indexes 0 to 73811151924273136404452586370firstmidlast58 > 52: discard indexes 8 to 113811151924273136404452586370firstmidlast58 < 63: discard indexes 13 and 143811151924273136404452586370first/mid/last58 found at index 12
  • A binary search only works on a sorted list.
  • Check the middle item. If it is the target, stop.
  • If the target is bigger, discard the middle item and all before it. If smaller, discard it and all after it.
  • Repeat on what is left until the target is found or nothing is left.
  • Each check halves the list: a divide and conquer algorithm.
Algorithms · searching

Binary search in code

  • first and last mark the part of the list still being searched.
  • The middle position is (first + last) DIV 2, using whole-number division.
  • With an even number of items this picks the lower of the two middle items.
  • Some textbooks take the higher middle item. Use one rule throughout, or the rule a question gives.
  • The loop ends when the target is found or first passes last.
OCR Exam Reference Language
first = 0
last = 14    // items holds 15 values: index 0 to 14
found = False
while first <= last AND found == False
    mid = (first + last) DIV 2
    if items[mid] == target then
        found = True
    elseif items[mid] < target then
        first = mid + 1
    else
        last = mid - 1
    endif
endwhile
Your answer
?A binary search looks for 40 in this sorted list of 15 items. Which items does it check, in order? Separate them with commas.

[3, 8, 11, 15, 19, 24, 27, 31, 36, 40, 44, 52, 58, 63, 70]

Algorithms · searching

Comparing the two searches

Worst-case checksLinear searchBinary search15 items15463 items6361,000 items1,0001002505007501,000Most checks needed (worst case)
Linear searchBinary search
Data must be sorted?NoYes
Most checks for 15 items154
Most checks for 1,000 items1,00010
CodeSimplerMore complex
  • Binary search is far more time-efficient on large sorted lists.
  • Linear search suits small or unsorted lists. Sorting a list first takes time too.
Quick check
?A shop's till stores the 30 items in a basket in the order they were scanned. Which search should check whether a pen was scanned?
Calculate
?A sorted list has 127 items. What is the greatest number of items a binary search will check?
Mission check

?How can 20 checks find one name among a million?
Mission 4

Why is it called a bubble sort?

Make a guess: Why is it called a bubble sort?

Algorithms · sorting

One pass

Bubble sort: pass 1swap25814no swap25814swap25184swap251488 is in place
  • A bubble sort compares each adjacent pair of items, starting at the front of the list.
  • If the pair is in the wrong order, swap them. Then move along one place and compare the next pair.
  • One trip through every pair is a pass.
  • After pass 1 of [5, 2, 8, 1, 4], the list is [2, 5, 1, 4, 8].
Your answer
?Do one pass of a bubble sort (into ascending order) on [6, 3, 9, 1, 7, 4]. What is the list after pass 1? Separate the numbers with commas.
Algorithms · sorting

Passes until sorted

Bubble sort: every passStart52814Pass 1251483 swapsPass 2214582 swapsPass 3124581 swapthe rest happen to be in order alreadyPass 4124580 swaps: stop
  • Keep making passes. Each pass carries the largest unsorted item to its final place.
  • Stop after a pass that makes no swaps: the list must be sorted.
  • [5, 2, 8, 1, 4] needs 3 passes with swaps, then a 4th pass with none to confirm it.
  • A list of n items needs at most n − 1 passes that make swaps.
Calculate
?A bubble sort stops after a pass with no swaps. How many passes does it make on [6, 3, 9, 1, 7, 4], including that last pass?
Algorithms · sorting

Bubble sort in code

  • The inner loop is one pass: it compares item i with item i + 1 and swaps them if needed.
  • the array items holds 6 values at indexes 0 to 5, so i runs from 0 to 4.
  • A swap needs a temporary variable, temp, to hold one value.
  • swapped records whether the pass changed anything. The outer loop repeats until a pass makes no swaps.
OCR Exam Reference Language
do
    swapped = False
    for i = 0 to 4
        if items[i] > items[i + 1] then
            temp = items[i]
            items[i] = items[i + 1]
            items[i + 1] = temp
            swapped = True
        endif
    next i
until swapped == False
Quick check
?A student swaps two items without a temporary variable. Before these two lines run, the first item holds 9 and the second holds 2. What do they hold afterwards?
OCR Exam Reference Language
items[i] = items[i + 1]
items[i + 1] = items[i]
Algorithms · sorting

Strengths and weaknesses

  • Simple to understand and to code.
  • Sorts in place: it needs almost no extra memory.
  • Quick on a nearly sorted list: a sorted list needs just one pass.
  • Slow on large lists: with 1,000 items, each pass makes 999 comparisons, and it may need 999 passes with swaps.
Calculate
?The code on screen 5 compares 5 pairs in every pass. How many comparisons does it make in total to sort [6, 3, 9, 1, 7, 4]?
Mission check

?Why is it called a bubble sort?
Mission 5

Why does a fast sort start by chopping a list into pieces?

Make a guess: Why does a fast sort start by chopping a list into pieces?

Algorithms · sorting

Split until single items

Merge sort62947183629471836294718362947183264917382469137812346789splitmerge (in order)one item: sorted
  • A merge sort first splits the list into two halves, then splits each half, and so on.
  • Splitting stops when every list holds one item. A list of one item is already sorted.
  • 8 items take 3 rounds of splitting: 8 → 4 + 4 → four lists of 2 → eight lists of 1.
  • Breaking a problem into smaller problems like this is divide and conquer.
Algorithms · sorting

Merge sorted lists

Merging two sorted listsList AList Bcompare1246913781 < 2output12246913782 < 3output123246913783 < 4output1234246913784 < 7output12345246913786 < 7output123466246913787 < 9output1234677246913788 < 9output1234678–24691378copy 9: nocomparisonoutput12346789
  • Now merge pairs of sorted lists into bigger sorted lists, until one list is left.
  • To merge, compare the first items of both lists and move the smaller to the new list. Repeat.
  • When one list is empty, copy the rest of the other across with no more comparisons.
  • Merging [2, 4, 6, 9] with [1, 3, 7, 8] takes 7 comparisons (see diagram).
Your answer
?Merge the sorted lists [3, 8, 9] and [1, 4, 10]. What is the merged list? Separate the numbers with commas.
Algorithms · sorting

Insertion sort

Insertion sortStart524613Insert 2254613Insert 4245613Insert 6245613Insert 1124563Insert 3123456green: sorted part · orange: item inserted · arrows: largeritems shifted right
  • An insertion sort builds a sorted part at the start of the list, one item at a time.
  • Take the next item. Shift each larger item in the sorted part one place right, then insert the item in the gap.
  • n items need n − 1 passes: the first item starts as the sorted part.
  • The diagram shows each pass on a list of 6 items.
OCR Exam Reference Language
for i = 1 to 5    // items holds 6 values: index 0 to 5
    current = items[i]
    pos = i
    while pos > 0 AND items[pos - 1] > current
        items[pos] = items[pos - 1]
        pos = pos - 1
    endwhile
    items[pos] = current
next i
Your answer
?An insertion sort is run on [7, 3, 5, 1, 6]. What is the list just after the 1 has been inserted? Separate the numbers with commas.
Algorithms · sorting

Comparing sorts

Bubble sortMerge sort
Large listsSlow: hundreds of thousands of comparisons for 1,000 itemsFast: under 9,000 comparisons for 1,000 items
MemorySorts in place, little extra memoryNeeds extra memory for the split lists
CodeSimpleMore complex
Nearly sorted listQuick if only a few items are out of placeStill splits and merges everything
  • Insertion sort is simple, sorts in place and is quick on nearly sorted lists, but slow on large unsorted ones.
Quick check
?A phone with plenty of free memory must sort 2 million photos into date order. Which sort suits it best?
Calculate
?How many comparisons does it take to merge [4, 5, 6] with [7, 8, 9]?
Mission check

?Why does a fast sort start by chopping a list into pieces?
Recap

Big ideas

  • Decomposition breaks a problem into sub-problems that can be solved separately.
  • Abstraction removes unnecessary detail so a model keeps only what the task needs.
  • An algorithm is a sequence of steps; start by identifying the inputs, processes and outputs.
  • Flowcharts, pseudocode and program code are three ways to write the same algorithm.
  • A trace table records each variable during a dry run; it reveals the output, the purpose and any logic error.
  • Syntax errors stop code running; logic errors give wrong results.
  • Linear search checks items one by one; it works on unsorted data but can need a check for every item.
  • Binary search needs sorted data; it checks the middle and halves the list each time, so it needs far fewer checks.
  • A bubble sort compares adjacent pairs and swaps any in the wrong order; one run through the list is a pass.
  • After each pass, the largest unsorted item is in place; stop when a pass makes no swaps.
  • It is simple and needs little memory, but it is slow for large lists.
  • Merge sort splits the list down to single items, then merges sorted lists back together: divide and conquer.
  • Merge sort is much faster on large lists but needs extra memory; bubble sort is simpler and sorts in place.
  • Insertion sort inserts each item into a growing sorted part at the start of the list.
🏆

Mini-lesson complete!

⭐⭐⭐

You've worked through Algorithms for OCR GCSE Computer Science (J277). 🎉

  1. Mission 1Why does the Tube map ignore real distances, yet still work?
  2. Mission 2How can you find a bug without running the program?
  3. Mission 3How can 20 checks find one name among a million?
  4. Mission 4Why is it called a bubble sort?
  5. Mission 5Why does a fast sort start by chopping a list into pieces?

Your stars: 0 / 0

Next: test yourself in the Verify stage.

📣 Smashed it? Share your score

Challenge a mate to beat your stars, or show a parent how you got on.

→ Back to GCSE Computer Science · OCR

Specification points and sources for this lesson are listed at the bottom of the page.

Sources (5)

The specification points and sources behind this lesson.

  1. 1 OCR GCSE J277 v3.1 spec, 2.1.1 and 2.1.2
  2. 2 OCR J277 v3.1 spec, 2.1.2 and 3c (Exam Reference Language)
  3. 3 OCR J277 v3.1 spec, 2.1.3 and 3c
  4. 4 OCR J277 June 2024 Paper 2, Q3(c), via physicsandmathstutor.com
  5. 5 London Museum, "How Harry Beck revolutionised the Tube map", https://www.londonmuseum.org.uk/collections/london-stories/harry-beck-revolutionised-tube-map/