Worked solution from the Computational thinking and Problem-solving Paper 3 Advanced Theory booklet, Part 1 of 2.
The array must be in order.
The elements must be sorted (in ascending or descending order) [1]
Set Found before the loop. The loop runs while the item is not found and the list is not used up. Test the middle item, then move the top up or the end down.
Found ← FALSE
NotInList ← FALSE
WHILE Found = FALSE AND NotInList = FALSE
CurrentItem ← (TopOfList + EndOfList) DIV 2
IF ToFind = Names[CurrentItem] THEN
Found ← TRUE
ELSE
IF TopOfList >= EndOfList THEN
NotInList ← TRUE
ELSE
IF ToFind > Names[CurrentItem] THEN
TopOfList ← CurrentItem + 1
ELSE
EndOfList ← CurrentItem - 1
ENDIF
ENDIF
ENDIF
ENDWHILEFound ← FALSE [1]
WHILE Found = FALSE AND NotInList = FALSE [1]
IF ToFind = Names[CurrentItem] THEN [1]
NotInList ← TRUE [1]
TopOfList ← CurrentItem + 1 [1]
Only the five blanks are marked.
Binary search halves the search area each time, so it is very fast on large arrays.
The Big O of a binary search is O(log2 n) [1]
The time taken grows logarithmically as the number of items grows: the search area is halved each time, so only a small number of comparisons are needed [1]
Another accepted point: Big O notation shows the time or space complexity of an algorithm.
▶ Starts at Q10 (1:05:59)
Starts at Q10 (1:05:59) · by Pseudocode Pro. 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.