Skip to content
Cambridge AS & A Level9618

Algorithms (A Level)

Computer Science 9618 Chapter Notes

Last updated November 2026

What this chapter covers

Algorithms
ShareWhatsAppPost

Algorithms (A Level) notes as a printable PDF.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Algorithms (A Level) notes as text: skim, search, and jump between subtopics.

~18 min read

1. Linear search

A linear search sequentially checks each element of the array. It carries on until the matching element is found, or the end of the array is reached.

It starts at the beginning of the array. It does not require the elements to be sorted. Two stopping conditions are needed, so the loop tests both.

``` Count ← 1 Found ← FALSE WHILE Found = FALSE AND Count <= EndOfList IF Widgets[Count] = ToFind THEN Found ← TRUE ELSE Count ← Count + 1 ENDIF ENDWHILE ```

Examiner insight

“A few candidates output ‘True’ and ‘False’, or another message, instead of the returning the required values.”

Worked example 14 marks

Complete the pseudocode to find an item in a 1D array `Widgets` of type STRING, using a linear search.

``` TopOfList ← 1 EndOfList ← 50000 INPUT ToFind (1) ...... NotInList ← FALSE Count ← TopOfList WHILE (2) ...... AND ...... IF (3) ...... THEN Found ← TRUE ENDIF Count ← Count + 1 IF (4) ...... THEN NotInList ← TRUE ENDIF ENDWHILE ```

  1. 1

    (1) `Found ← FALSE` [1]

  2. 2

    (2) `Found = FALSE AND NotInList = FALSE`, or `Count <= EndOfList` as the second condition [1]

  3. 3

    (3) `ToFind = Widgets[Count]` [1]

  4. 4

    (4) `Found = FALSE AND Count > EndOfList` [1]

2. Binary search

A binary search finds the position of a target value within an array by repeatedly halving the search field. It finds the mid-point of the array and decides which side holds the item. It discards the half that does not.

The condition: the elements must be sorted, in ascending or descending order. The search starts in the middle of the array, not at the beginning.

``` FUNCTION PartSearch(Target : STRING) RETURNS INTEGER Left ← 1 Right ← 1000000 WHILE Left <= Right Mid ← (Left + Right) DIV 2 IF PartName[Mid] = Target THEN RETURN Mid ELSE IF PartName[Mid] < Target THEN Left ← Mid + 1 ELSE Right ← Mid - 1 ENDIF ENDIF ENDWHILE RETURN -1 ENDFUNCTION ```

Worked example 15 marks

Complete the given pseudocode to find an item in a 1D array `Names` of type STRING using a binary search.

``` TopOfList ← 1 EndOfList ← 100000 INPUT ToFind (1) ...... NotInList ← FALSE WHILE (2) ...... AND ...... CurrentItem ← (TopOfList + EndOfList) DIV 2 IF (3) ...... THEN Found ← TRUE ELSE IF TopOfList >= EndOfList THEN (4) ...... ELSE IF ToFind > Names[CurrentItem] THEN (5) ...... ELSE EndOfList ← CurrentItem - 1 ENDIF ENDIF ENDIF ENDWHILE ```

  1. 1

    (1) `Found ← FALSE` [1]

  2. 2

    (2) `Found = FALSE AND NotInList = FALSE` [1]

  3. 3

    (3) `ToFind = Names[CurrentItem]` [1]

  4. 4

    (4) `NotInList ← TRUE` [1]

  5. 5

    (5) `TopOfList ← CurrentItem + 1` [1]

3. Comparing searches with Big O

Algorithms that do the same task are compared by the time taken and the memory used. Big O notation is used to indicate the time / space complexity of an algorithm.

For a linear search the worst case is O(n). The time increases linearly as the number of items increases linearly. For a binary search it is O(log₂ n). The time increases logarithmically as the number of items increases linearly.

A binary search usually makes many fewer comparisons than a linear search, but it needs the elements sorted.

linear search: O(n)

binary search: O(log₂ n)

Worked example 13 marks

Two examples of searching algorithms are a linear search and a binary search. Describe how increasing the number of data items in the file to be searched affects the time efficiency of these search algorithms. Refer to Big O notation in your answer.

  1. 1

    Linear search: the time increases linearly as the number of search items increases linearly [1]

  2. 2

    Linear search worst case is O(n) [1]

  3. 3

    Binary search: the time increases logarithmically as the number of items increases linearly (or linearly as the items increase exponentially) [1]

  4. 4

    Binary search worst case is O(logn) or O(log₂n) (any three of these four points score)

4. Bubble sort

A bubble sort compares neighbouring elements and swaps them when they are out of order. The comparison sets the order: `>` gives ascending order. Reversing it gives descending order.

It needs an outer loop and an inner loop. The inner loop stops at the second-last element, so `Index + 1` is never outside the array. `Flag` is set to FALSE once before each inner loop and to TRUE only when a swap happens. A pass with no swap ends the sort.

With two arrays or two columns, the other column value must also be swapped. The temporary swap variable has the same data type as the value it holds.

``` Flag ← TRUE WHILE Flag = TRUE Flag ← FALSE FOR Index ← 1 TO N - 1 IF Data[Index] > Data[Index + 1] THEN Temp ← Data[Index] Data[Index] ← Data[Index + 1] Data[Index + 1] ← Temp Flag ← TRUE ENDIF NEXT Index ENDWHILE ```

Examiner insight

“Setting a flag to TRUE when elements were swapped but also setting it to FALSE if they were not.” “Some solutions lost this mark by declaring the temporary swap variable as a string rather than an integer.”

Worked example 14 marks

A bubble sort arranges the list 4, 2, 5, 1 into ascending order. `Flag` is set to FALSE before each pass and to TRUE when a swap happens. Write the list at the end of each pass. State how many passes are made.

  1. 1

    Pass 1: 4 and 2 swap, 5 and 1 swap, giving 2, 4, 1, 5 [1]

  2. 2

    Pass 2: 4 and 1 swap, giving 2, 1, 4, 5 [1]

  3. 3

    Pass 3: 2 and 1 swap, giving 1, 2, 4, 5 [1]

  4. 4

    Pass 4: no swap, so `Flag` stays FALSE and the sort ends. 4 passes in all [1]

5. Insertion sort

An insertion sort takes each element in turn, starting with the second. The element being inserted is held in temporary storage. Larger elements are moved to the adjacent element until the insertion position is found. The held element is then put back outside the inner loop.

With two arrays, the elements of both are moved and both are put back. Each index then still refers to the same person.

``` FOR Index ← 2 TO 1000 Value ← DataArray[Index] Position ← Index - 1 WHILE Position >= 1 AND DataArray[Position] > Value DataArray[Position + 1] ← DataArray[Position] Position ← Position - 1 ENDWHILE DataArray[Position + 1] ← Value NEXT Index ```

Examiner insight

“A common error was in the second loop where a bubble sort was written instead of an insertion sort.” “There were many partially correct solutions, mostly related to the temporary storage and insertion parts of the algorithm.”

Worked example 14 marks

A 1D array `DataArray` holds up to 1000 elements of type integer and needs to be sorted in ascending order. Write the pseudocode for an insertion sort to sort the array into ascending order. Use the identifiers `Index`, `Position`, `DataArray` and `Value`. The first line has been written for you.

``` FOR Index ← 2 TO 1000 ```

  1. 1

    `Value ← DataArray[Index]`: temporary assignment of the element being inserted, before the inner loop [1]

  2. 2

    `Position ← Index - 1` and `WHILE Position >= 1 AND DataArray[Position] > Value`: an inner loop that checks the current content is greater than `Value` [1]

  3. 3

    `DataArray[Position + 1] ← DataArray[Position]`: moving data to the adjacent element [1]

  4. 4

    `Position ← Position - 1`: updating `Position` (any four of the six points score)

  5. 5

    `DataArray[Position + 1] ← Value`: re-insertion of the element outside the inner loop [1]

6. What affects sorting performance

The performance of a sorting routine may depend on two things. One is the initial order of the data. A sort should improve if the data is already partially sorted. It is likely to be worse if the data is completely out of order.

The other is the number of items to be sorted. The sort may take longer if the number is larger. The worst-case time complexity of an insertion sort is O(n²).

Sort only the elements in use. Empty elements filled with a value such as -1 would be sorted to the front.

insertion sort, worst case: O(n²)

Examiner insight

“Some candidates included the empty array elements in the insertion sort. These were all initialised to –1 in an earlier question part which meant that these were now the first elements in the array instead of the jobs with the highest priority.”

Worked example 12 marks

Describe two ways in which the performance of a sort routine is affected by the data to be sorted.

  1. 1

    The performance should improve if the data is already partially sorted, and is likely to be worse if it is completely out of order [1]

  2. 2

    The sort may take longer if the number of items to be sorted is larger, and less time if the number is fewer [1]

7. Stacks and queues

An array is an Abstract Data Type (ADT). Other ADTs are a stack, a queue, a linked list, a binary tree and a graph. An ADT can be built from a built-in type or from another ADT. A stack or queue can be built from a 1D array.

A stack is used to evaluate an RPN expression. The operands are popped from the stack in the reverse order to how they were pushed. In the code, `TopOfStack` starts at 0 and the array is `Stack[1:100]`.

``` PROCEDURE Push(Item : STRING) IF TopOfStack = 100 THEN OUTPUT "Stack full" ELSE TopOfStack ← TopOfStack + 1 Stack[TopOfStack] ← Item ENDIF ENDPROCEDURE ```

A linear queue keeps `QueueHead` and `QueueTail`, both starting at -1, and `NumberItems`, starting at 0. The array is `Queue[0:99]`. Items join at the tail and leave from the head.

``` FUNCTION Enqueue(TheData : STRING) RETURNS BOOLEAN IF QueueTail = 99 THEN RETURN FALSE ELSE IF QueueHead = -1 THEN QueueHead ← 0 ENDIF QueueTail ← QueueTail + 1 Queue[QueueTail] ← TheData NumberItems ← NumberItems + 1 RETURN TRUE ENDIF ENDFUNCTION ```

Worked example 13 marks

A linear queue is held in the global 1D array `Queue`, with global pointers `QueueHead` and `QueueTail` and the global variable `NumberItems`. The function `Dequeue()` returns the string "False" if the queue is empty. If the queue is not empty, the function returns the next element in the queue. The function updates the appropriate pointer(s) and updates `NumberItems`. Write program code for `Dequeue()`.

  1. 1

    `FUNCTION Dequeue() RETURNS STRING`, checking if the queue is empty (`IF NumberItems = 0`) and returning "False" [1]

  2. 2

    otherwise `ReturnValue ← Queue[QueueHead]`, returned at the end [1]

  3. 3

    `QueueHead ← QueueHead + 1` and `NumberItems ← NumberItems - 1`, done before the `RETURN` [1]

8. Linked lists, binary trees and graphs

A linked list is a list of nodes. Each node holds data and a pointer to the next node. The last pointer is a null pointer, written -1. To output the list, start at the first node and follow the pointers until the null pointer. To insert at the end, store the data in the first empty node with pointer -1. Follow the pointers to the last node and change its pointer to the new node. Then move the start of the empty list on to the next empty node.

A binary tree can be stored as a linked list of nodes, each with a left pointer, data and a right pointer. A 1D array of records holds the nodes. To search, compare the item with the node. Go left if it is smaller, go right if it is larger, stop when it is equal or the pointer is -1.

A graph is an ADT that gives structure to the relationships between nodes. It suits a map of towns joined by roads, where Dijkstra's algorithm finds the shortest distance. In AI a problem can be solved as finding a path in a graph.

Examiner insight

“Few candidates gave the correct term. Many just gave ‘Pointer’ as the answer.” “Candidates need to ensure that the link arrow starts from the pointer section of the (previous) node.”

Worked example 14 marks

A binary tree is stored as a linked list of nodes in a 1D array of records `BinTree`. Each record contains a left pointer, data and a right pointer. -1 is used to represent a null pointer. The following pseudocode represents a function that searches for an element in `BinTree`. It returns the index of the record if the element is found, or it returns a null pointer if the element is not found. Complete the pseudocode for the function.

``` FUNCTION SearchTree(Item : STRING) (1) ...... NowPtr ← (2) ...... WHILE NowPtr <> -1 IF (3) ...... THEN NowPtr ← BinTree[NowPtr].LeftPtr ELSE IF BinTree[NowPtr].Data < Item THEN (4) ...... ELSE RETURN NowPtr ENDIF ENDIF ENDWHILE RETURN NowPtr ENDFUNCTION ```

  1. 1

    (1) `RETURNS INTEGER` [1]

  2. 2

    (2) `RootPtr` [1]

  3. 3

    (3) `BinTree[NowPtr].Data > Item` [1]

  4. 4

    (4) `NowPtr ← BinTree[NowPtr].RightPtr` [1]

Recap

  • Linear search: check each element in turn until found or the end is reached. The data need not be sorted. Worst case O(n).
  • Binary search: the data must be sorted. Find `Mid`, discard the half without the item. Worst case O(log₂ n).
  • Bubble sort: swap neighbours. Reset `Flag` once before the inner loop. The inner loop stops at the second-last element.
  • Insertion sort: hold the value in temporary storage, move larger values up one place, put the value back outside the loop.
  • Sort performance depends on the initial order of the data and the number of items. Insertion sort worst case is O(n²).
  • Stack: items are popped in the reverse order to how they were pushed. Queue: join at the tail, leave from the head.
  • Linked list: follow pointers to the null pointer, -1. Binary tree: left if smaller, right if larger. A graph shows relationships between nodes.

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. The array `Scores[1:6]` holds 14, 9, 23, 9, 30, 5. A linear search looks for 23. A second linear search looks for 8. State the number of comparisons each search makes.2 marks
    Answer
    1. 23 is found at position 3: 3 comparisons.
    2. 8: the array is not sorted, so all 6 elements are checked: 6 comparisons.

    Trap: Stopping at 9 because 8 is smaller. A linear search stops only when it finds the item or reaches the end.

  2. The sorted array `Codes[1:9]` holds 3, 8, 12, 15, 21, 27, 34, 40, 52. A binary search uses `Mid ← (Left + Right) DIV 2`. Give each value of `Left`, `Right` and `Mid` when searching for 34. State the position at which 34 is found.4 marks
    Answer
    1. First pass: `Left = 1`, `Right = 9`, `Mid = 10 DIV 2 = 5`. `Codes[5]` is 21.
    2. 34 > 21, so `Left ← Mid + 1 = 6`.
    3. Second pass: `Left = 6`, `Right = 9`, `Mid = 15 DIV 2 = 7`.
    4. `Codes[7]` is 34, so it is found at position 7.

    Trap: `DIV` discards the fraction. (6 + 9) ÷ 2 = 7.5 gives 7, not 8.

  3. A bubble sort with a flag arranges the list 2, 7, 4, 9 into descending order. Write the list at the end of each pass. State how many passes are made.4 marks
    Answer
    1. Descending: swap when the left value is smaller. Pass 1: 7, 4, 9, 2.
    2. Pass 2: 7, 9, 4, 2. Pass 3: 9, 7, 4, 2.
    3. Pass 4: no swap, so `Flag` stays FALSE. 4 passes in all.

    Trap: Using `>` for the comparison. Examiners reported a reversed comparison operator, which sorts the array the wrong way round.

  4. An insertion sort arranges the list 7, 4, 9, 2 into ascending order. Write the list after each value is inserted. State how many times a value is moved up one place.4 marks
    Answer
    1. Insert 4: 7 moves up one place: 4, 7, 9, 2. Insert 9: no moves.
    2. Insert 2: 9, 7 and 4 each move up one place: 2, 4, 7, 9.
    3. Moves: 1 + 0 + 3 = 4.

    Trap: Starting at the first value. The outer loop starts at the second element, and a value already in place causes no moves.

  5. A stack holds at most three integers and starts empty. The operations are: Push(4), Push(9), Pop, Push(2), Push(6), Push(8). State the value Pop returns, the final contents from bottom to top, and the operation that fails.3 marks
    Answer
    1. Pop returns 9, the last item pushed.
    2. At the end the stack holds 4, 2, 6 from bottom to top.
    3. Push(8) fails, because the stack already holds three items and outputs "Stack full".

    Trap: Saying Pop returns 4. That removes the first item pushed, which is how a queue behaves.

  6. A linear queue uses `Queue[0:99]`, with `QueueHead` and `QueueTail` starting at -1 and `NumberItems` starting at 0. These operations are done in order: Enqueue("A"), Enqueue("B"), Enqueue("C"), Dequeue(), Enqueue("D"). State the value returned by Dequeue(), then the final values of `QueueHead`, `QueueTail` and `NumberItems`.4 marks
    Answer
    1. After three Enqueue calls: `QueueHead = 0`, `QueueTail = 2`, `NumberItems = 3`.
    2. Dequeue() returns "A", then `QueueHead = 1`, `NumberItems = 2`.
    3. Enqueue("D") stores "D" at index 3. Final values: `QueueHead = 1`, `QueueTail = 3`, `NumberItems = 3`.

    Trap: Changing `QueueTail` in Dequeue. Only `QueueHead` and `NumberItems` change when an item leaves.

  7. A linked list is stored in a 2D array. Each node has data and a pointer. A pointer of -1 marks the end of the list. `StartLinkedList` is 1. Node 3 is unused. (a) Write the data in list order. (b) The value 40 must be inserted between 30 and 50, using node 3. State what is stored in node 3 and which other pointer changes. | node | data | pointer | | --- | --- | --- | | 0 | 30 | 2 | | 1 | 10 | 0 | | 2 | 50 | -1 |4 marks
    Answer
    1. (a)
    2. Start at node 1: 10. Its pointer is 0, so node 0: 30. Its pointer is 2, so node 2: 50. Its pointer is -1, so stop. The order is 10, 30, 50.
    3. (b)
    4. Node 3 stores data 40 and pointer 2, the node that holds 50.
    5. The pointer of node 0 changes from 2 to 3. The list is now 10, 30, 40, 50.

    Trap: Reading the array in index order, giving 30, 10, 50. Follow the pointers from the start.

  8. Values are added to an empty ordered binary tree in this order: 35, 20, 50, 10, 30, 45. A smaller value goes to the left. State the left and right children of the node 20. List the nodes visited, in order, when searching for 45.3 marks
    Answer
    1. 35 is the root; 20 and 50 are its children; 10 goes left of 20. 30 is smaller than 35 but larger than 20, so the children of 20 are 10 (left) and 30 (right).
    2. Searching for 45 visits 35, then 50, then 45.

    Trap: Placing 30 by comparing with the root only. Compare with each node on the way down.

  9. A walking club stores distances in km in `Distance[1:50]` (INTEGER) and the matching town names in `Town[1:50]` (STRING). Write pseudocode for a bubble sort that arranges the data into ascending order of distance, so that each town stays with its distance. Use a flag so that the sort ends when a pass makes no swap.6 marks
    Answer
    1. ``` Flag ← TRUE WHILE Flag = TRUE Flag ← FALSE FOR Index ← 1 TO 49 IF Distance[Index] > Distance[Index + 1] THEN TempD ← Distance[Index] TempT ← Town[Index] Distance[Index] ← Distance[Index + 1] Town[Index] ← Town[Index + 1] Distance[Index + 1] ← TempD Town[Index + 1] ← TempT Flag ← TRUE ENDIF NEXT Index ENDWHILE ```
    2. 1 mark each: `Flag ← FALSE` before the inner loop of a loop that runs while `Flag = TRUE`; inner loop to 49; `>` for ascending order; `Distance` swapped via a temporary; `Town` swapped via a string temporary; `Flag ← TRUE` on a swap.

    Trap: Swapping only `Distance`, as examiners reported, or running the inner loop to 50 so `Index + 1` is out of bounds.

  10. A race stores up to 40 runners: names in `Runner[1:40]` (STRING) and times in seconds in `Time[1:40]` (INTEGER). Elements 1 to `NumRunners` are in use; every unused element of `Time` holds -1. (a) Write pseudocode for an insertion sort into ascending order of time that keeps each name with its time. Use `Index`, `Position`, `TempTime` and `TempName`. (b) State the worst-case Big O time complexity of an insertion sort, and one property of the times that would make the sort take less time.8 marks
    Answer
    1. ``` FOR Index ← 2 TO NumRunners TempTime ← Time[Index] TempName ← Runner[Index] Position ← Index - 1 WHILE Position >= 1 AND Time[Position] > TempTime Time[Position + 1] ← Time[Position] Runner[Position + 1] ← Runner[Position] Position ← Position - 1 ENDWHILE Time[Position + 1] ← TempTime Runner[Position + 1] ← TempName NEXT Index ```
    2. (a) 1 mark each: loop to `NumRunners`; both temporaries set; inner loop condition; both arrays moved up; `Position` decremented; both re-inserted.
    3. (b) O(n²). Faster if the times are already partially sorted.

    Trap: Looping to 40, not `NumRunners`, so the unused -1 times sort to the front, as examiners reported.

Say this, not that

Wording that loses the mark, against the wording the mark scheme credits.

Loses the markGets the mark
‘Pointer’ for the value that ends a linked listnull pointer
A second loop that swaps neighbours (a bubble sort) in an insertion sortA second loop that moves data to the adjacent element, then re-insertion of the held value outside the loop
Swapping only one of the two data itemsMoving all the data elements to the next array elements, so each index still matches
Sorting every element, including the empty -1 onesSort only the elements in use, with the count of stored items controlling the loop

Frequently asked questions

How does a linear search work?
A linear search sequentially checks each element of the array, starting at the beginning. It carries on until the matching element is found or the end of the array is reached. It does not require the elements to be sorted, and the loop needs two stopping conditions.
How does a binary search find an item in an array?
A binary search finds the mid-point of the array and decides which side holds the item, then discards the half that does not. The elements must be sorted, in ascending or descending order. The search starts in the middle of the array, not at the beginning.
How do linear search and binary search compare using Big O notation?
For a linear search the worst case is O(n), so the time increases linearly as the number of items increases. For a binary search it is O(log2 n), so the time increases logarithmically. A binary search usually makes many fewer comparisons than a linear search, but it needs the elements sorted.
How does a bubble sort work?
A bubble sort compares neighbouring elements and swaps them when they are out of order. The comparison sets the order: > gives ascending order and reversing it gives descending order. A Flag is set to FALSE before each inner loop and to TRUE only when a swap happens, so a pass with no swap ends the sort.
How does an insertion sort work?
An insertion sort takes each element in turn, starting with the second. The element being inserted is held in temporary storage, and larger elements are moved to the adjacent element until the insertion position is found. The held element is then put back outside the inner loop. Its worst-case time complexity is O(n^2).
Why must a sort only include the elements in use?
If the array has empty elements, sorting every element includes them. Empty elements filled with a value such as -1 would be sorted to the front, ahead of the real items. Sort only the elements in use, with the count of stored items controlling the loop.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters