SYLLABUS 7.4 · PAPER 2 · ALSO FOR 0984 AND 2210

Standard methods: linear search, bubble sort, totalling and counting

Paper 2 expects you to write and recognise a small set of standard algorithms. Most longer answers are built from them, so it pays to be able to write each one without thinking.

Totalling, counting, maximum, minimum and average

A total starts at 0 and has each value added to it. A count starts at 0 and goes up by 1 each time something happens. For a maximum, start with the first value, or a value lower than any possible one, and replace it whenever a bigger one comes along; a minimum works the other way. The average is the total divided by how many values there were, worked out after the loop.

Total <- 0
Count <- 0
Highest <- Scores[1]
FOR Index <- 1 TO 10
    Total <- Total + Scores[Index]
    IF Scores[Index] >= 50 THEN
        Count <- Count + 1
    ENDIF
    IF Scores[Index] > Highest THEN
        Highest <- Scores[Index]
    ENDIF
NEXT Index
Average <- Total / 10

Linear search

A linear search looks at each item in turn, from the first, until it finds the one it wants or reaches the end. A flag records whether it was found, and a condition-controlled loop lets it stop as soon as it is.

Found <- FALSE
Index <- 1
WHILE Index <= 10 AND NOT Found DO
    IF Names[Index] = Wanted THEN
        Found <- TRUE
    ELSE
        Index <- Index + 1
    ENDIF
ENDWHILE

Bubble sort

A bubble sort compares each pair of neighbouring items and swaps them if they are in the wrong order. After one pass the biggest item has reached the end, so each later pass can stop one place sooner. A flag records whether any swap happened; a pass with no swaps means the list is sorted and the sort can stop.

The swap needs a temporary variable: copy one item into Temp, copy the other item over it, then copy Temp into the second place.

Where marks go

  • Not setting a total or count to 0 before the loop.
  • Working out the average inside the loop, or dividing by the wrong number.
  • Starting a maximum at 0, which is wrong if every value could be negative.
  • Swapping without a temporary variable, so both places end up with the same value.
  • Using a FOR loop for a search and then not stopping it once the item is found.

Try a question

3 MARKS · MARKED ON THIS PAGE

A teacher has marked a spelling test for a class of 10 students. A mark of 50 or more is a pass. Write pseudocode that: - declares an array Marks : ARRAY[1:10] OF INTEGER - inputs the ten marks into Marks, in order - uses a variable PassCount to count how many marks are 50 or more - outputs only the value of PassCount, once, after all the marks have been checked.

solutionPseudocode
Loading...
Type your answer first.