Worked solution from the Computational thinking and Problem-solving Paper 3 Advanced Theory booklet, Part 1 of 2.
Upper must start at the last index, 99. Stop if Upper drops below Lower. Move Lower or Upper past Mid. Stop when the name is found.
Lower ← 0
Upper ← 99
Mid ← 0
Exit ← FALSE
OUTPUT "Enter the name to be found "
INPUT Target
REPEAT
IF Upper < Lower THEN
OUTPUT Target, " does not exist"
Exit ← TRUE
ENDIF
Mid ← Lower + (Upper - Lower + 1) DIV 2
IF Names[Mid] < Target THEN
Lower ← Mid + 1
ENDIF
IF Names[Mid] > Target THEN
Upper ← Mid - 1
ENDIF
IF Names[Mid] = Target THEN
OUTPUT Target, " was found at location ", Mid
Exit ← TRUE
ENDIF
UNTIL ExitUpper ← 99 [1]
IF Upper < Lower THEN [1]
Lower ← Mid + 1 [1]
Upper ← Mid - 1 [1]
IF Names[Mid] = Target THEN [1]
UNTIL Exit (or UNTIL Exit = TRUE) [1]
Write:
O(n) [1]
Write any two of these:
O(log n) means the algorithm takes logarithmic time [1]
The time taken goes up linearly while the number of items rises exponentially [1]
Other points that also score: it is the worst case time complexity for a binary search.
▶ Whole paper
Video solution of the whole paper · by MAK CS. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.