📗 Paper 4 · 4.4 Algorithms
4.4.1 Sorting Algorithms
Cambridge 9618 · International A Level Computer Science · ~18 min read
Notes
Video
Slides
Quiz
Worksheet

Why Sorting Matters

Sorting is a fundamental operation in computing. Sorted data enables efficient searching (binary search requires sorted data), presentation of ordered results, and efficient merging of datasets. Cambridge 9618 Paper 4 requires knowledge of four sorting algorithms: bubble sort, insertion sort, merge sort, and quick sort.

Bubble Sort

🫧 Bubble Sort
O(n²) average O(n) best case Stable
Repeatedly compare ADJACENT pairs and swap them if in the wrong order. After each pass, the LARGEST unsorted element "bubbles" to the correct position at the end. Continue until no swaps occur in a full pass (early termination).

Key facts: Simple to implement. Efficient only for nearly-sorted data (O(n) best case with early termination flag). Stable sort (equal elements preserve original order). In-place (O(1) extra space).
Pass 1: [64, 34, 25, 12, 22]
 Compare 64,34 → swap: [34, 64, 25, 12, 22]
 Compare 64,25 → swap: [34, 25, 64, 12, 22]
 Compare 64,12 → swap: [34, 25, 12, 64, 22]
 Compare 64,22 → swap: [34, 25, 12, 22, 64✓]
Pass 2: Compare 34,25 → swap, 34,12 → swap, ... → [25, 12, 22, 34✓, 64✓]
...continue until no swaps → sorted!
// Bubble sort with early termination
PROCEDURE BubbleSort(Arr, n)
  FOR i1 TO n-1
    swappedFALSE
    FOR j1 TO n-i
      IF Arr[j] > Arr[j+1] THEN
        Swap(Arr[j], Arr[j+1])
        swappedTRUE
      ENDIF
    NEXT j
    IF NOT swapped THEN EXIT FOR  // already sorted
  NEXT i
ENDPROCEDURE

Insertion Sort

📥 Insertion Sort
O(n²) average O(n) best case Stable
Builds a sorted portion one element at a time. For each new element, insert it into the correct position in the already-sorted portion by shifting elements right. Like sorting playing cards in your hand.

Key facts: Very efficient for small or nearly-sorted datasets. O(n) best case (already sorted — no shifts needed). Stable sort. In-place. Better than bubble sort in practice for most cases.
[5, 3, 8, 1, 9]
i=2: key=3. 3<5 → shift 5 right. Insert 3: [3,5, 8, 1, 9]
i=3: key=8. 8>5 → no shift. Insert 8: [3, 5, 8, 1, 9]
i=4: key=1. Shift 8,5,3 right. Insert 1: [1, 3, 5, 8, 9]
i=5: key=9. 9>8 → no shift. Done: [1, 3, 5, 8, 9] ✓
// Insertion sort
PROCEDURE InsertionSort(Arr, n)
  FOR i2 TO n
    keyArr[i]
    ji - 1
    WHILE j1 AND Arr[j] > key
      Arr[j+1] ← Arr[j]  // shift right
      jj - 1
    ENDWHILE
    Arr[j+1] ← key  // insert
  NEXT i
ENDPROCEDURE

Merge Sort

🔀 Merge Sort
O(n log n) all cases Stable O(n) extra space
A divide-and-conquer algorithm. Recursively DIVIDE the array in half until each sub-array has one element (already sorted). Then MERGE pairs of sorted sub-arrays back together.

Key facts: Guaranteed O(n log n) — not affected by input order. Stable. But requires O(n) extra memory for the temporary merge buffer. Best for large datasets where predictable performance is needed.
[38, 27, 43, 3]
Divide: [38, 27] | [43, 3]
Divide: [38] | [27] | [43] | [3]
Merge [38]+[27]: compare 38 vs 27 → [27, 38]
Merge [43]+[3]: compare 43 vs 3 → [3, 43]
Merge [27,38]+[3,43]: 27>3→[3], 27<43→[3,27], 38<43→[3,27,38], [3,27,38,43] ✓

Quick Sort

⚡ Quick Sort
O(n log n) average O(n²) worst case Not stable In-place
Divide-and-conquer. Choose a PIVOT element. Partition the array into elements < pivot (left) and elements > pivot (right). Recursively sort each partition.

Key facts: Average O(n log n) — fastest in practice. Worst case O(n²) when pivot is always the smallest or largest (sorted/reverse-sorted input). In-place (O(log n) stack space for recursion). Not stable. Pivot choice matters — middle or random pivot avoids worst case.
[8, 3, 6, 1, 9, 4]  // pivot = 4 (last element)
Partition: elements < 4: [3, 1] | pivot: [4] | elements > 4: [8, 6, 9]
Recursively sort [3, 1] and [8, 6, 9]
[3,1]: pivot=1 → [1,3]
[8,6,9]: pivot=9 → [6,8] | 9 → [6,8,9]
Final: [1, 3, 4, 6, 8, 9] ✓

Summary Comparison

AlgorithmBest CaseAverage CaseWorst CaseSpaceStable?
Bubble SortO(n)O(n²)O(n²)O(1)✅ Yes
Insertion SortO(n)O(n²)O(n²)O(1)✅ Yes
Merge SortO(n log n)O(n log n)O(n log n)O(n)✅ Yes
Quick SortO(n log n)O(n log n)O(n²)O(log n)❌ No

When to choose which algorithm:

  • Bubble/Insertion sort: Small datasets (<20 elements) or nearly-sorted data; when simplicity matters
  • Merge sort: Large datasets; when guaranteed O(n log n) is needed; when stability matters; when sorting linked lists
  • Quick sort: General purpose; large datasets in practice (best constant factor despite same O notation as merge)
Cambridge 9618 exam tip: Know how to TRACE each algorithm on a given small array — examiners frequently give 5-6 element arrays and ask for the state after each pass or step. For bubble sort: show comparisons and swaps pass-by-pass. For insertion sort: show the sorted portion growing and where each key is inserted. For merge sort: show the divide steps then the merge steps. For quick sort: show the pivot and partition. Know time complexities for best/average/worst case. "Stable" means equal elements maintain their original relative order — important when sorting objects with multiple fields.
⚠️ Common Mistakes
  • Forgetting early termination in bubble sort — without the swap flag (swapped = FALSE at start of each pass), bubble sort is always O(n²). WITH the flag, it exits early if the array becomes sorted mid-way, giving O(n) best case.
  • Insertion sort starting index — insertion sort starts from index 2 (the SECOND element), treating the first element as an already-sorted list of one. Starting at index 1 misses the first element.
  • Quick sort worst case — O(n²) occurs when the pivot is always the minimum or maximum element (e.g. sorted array with first/last pivot choice). Always mention this when describing quick sort.
  • Merge sort space — merge sort requires O(n) EXTRA memory for the temporary arrays used during merging. It is NOT in-place. Quick sort is in-place (O(log n) stack space for recursion only).
  • Stability — only bubble sort, insertion sort, and merge sort are stable. Quick sort is NOT stable — equal elements may be reordered. This matters when sorting records with multiple keys.
✅ Notes completed!
Video coming soon
Click slide or press arrow keys to navigate

Worksheet — 4.4.1 Sorting Algorithms

8 questions · Cambridge 9618 standard

Q1Trace bubble sort on the array [5, 1, 4, 2, 8]. Show the state of the array after each complete pass. Use the swap flag for early termination where possible.[5]
✅ Mark scheme
Pass 1: [5,1]→swap [1,5]; [5,4]→swap [1,4,5]; [5,2]→swap [1,4,2,5]; [5,8]→no swap. After pass 1: [1, 4, 2, 5, 8] swapped=TRUE [1]; Pass 2: [1,4]→no swap; [4,2]→swap [1,2,4]; [4,5]→no swap. After pass 2: [1, 2, 4, 5, 8] swapped=TRUE [1]; Pass 3: [1,2]→no swap; [2,4]→no swap; [4,5]→no swap. After pass 3: [1, 2, 4, 5, 8] swapped=FALSE → early termination [1]; Award 1 mark per correct pass state [3 marks], 1 mark for showing early termination flag [1], 1 mark for identifying no swap on pass 3 causes exit [1]. Total 5 marks.
Q2Trace insertion sort on [29, 10, 14, 37, 13]. Show the sorted portion after each step (each time a new element is inserted).[4]
✅ Mark scheme
Start: sorted=[29] unsorted=[10,14,37,13] [1]; i=2, key=10: 10<29 shift 29 right, insert 10 → sorted=[10,29] [1]; i=3, key=14: 14<29 shift, 14>10 stop, insert → sorted=[10,14,29] [1]; i=4, key=37: 37>29 no shift, insert → sorted=[10,14,29,37] [1]; i=5, key=13: 13<37,29,14 shift all, 13>10 stop, insert → sorted=[10,13,14,29,37] ✓ [1 bonus]. Award 1 per correct step showing sorted portion. Max 4 marks.
Q3Explain the divide-and-conquer approach used by merge sort. State the two main phases and what happens in each.[4]
✅ Mark scheme
Divide phase: the array is repeatedly split in half — the left half and right half are each split again, recursively, until each sub-array contains only one element [1]; a single-element array is trivially sorted (base case) [1]; Merge phase: pairs of sorted sub-arrays are merged back together by comparing their front elements — the smaller goes into the merged array first; this repeats until one sub-array is exhausted, then the remainder is appended [1]; the merge phase produces larger and larger sorted arrays until the entire array is sorted [1]. The key insight is that merging two already-sorted arrays takes O(n) time, and the log n levels of division give O(n log n) total.
Q4Quick sort uses a pivot. Trace one partitioning step on [8, 3, 6, 1, 9, 4] using the last element (4) as pivot. Show the left partition, pivot, and right partition.[3]
✅ Mark scheme
Pivot = 4 (last element) [1]; Left partition (elements < 4): [3, 1] [1]; Right partition (elements > 4): [8, 6, 9] [1]; After one partition: [3, 1] | 4 | [8, 6, 9] — 4 is now in its FINAL sorted position. Recursively sort [3,1] → [1,3] and [8,6,9] → [6,8,9]. Final: [1,3,4,6,8,9]. Award all 3 marks for correct identification of pivot, left and right partitions, noting pivot is in final position.
Q5State the worst-case time complexity of quick sort and describe the input scenario that causes it. Explain how this can be avoided.[3]
✅ Mark scheme
Worst case O(n²) [1]; occurs when the pivot chosen is always the minimum or maximum element of the current partition — this creates highly unbalanced partitions (one side has n-1 elements, the other has 0); this happens when the array is already sorted (or reverse-sorted) and the pivot is always the first or last element [1]; avoidance: choose the pivot more carefully — options: (a) median-of-three: compare first, middle, and last elements and use the median as pivot; (b) random pivot selection: randomly choose a pivot position — makes worst case extremely unlikely; (c) use the middle element as pivot rather than first/last [1].
Q6Explain what is meant by a "stable" sorting algorithm. State which of the four sorting algorithms (bubble, insertion, merge, quick) are stable and which are not.[3]
✅ Mark scheme
A stable sorting algorithm preserves the ORIGINAL RELATIVE ORDER of elements that are equal (have the same sort key) [1]; example: if sorting [(Alice, 87), (Bob, 92), (Carol, 87)] by score, a stable sort would output Alice before Carol since Alice appears first in the original; an unstable sort might output Carol before Alice despite equal scores [1]; Stable: bubble sort, insertion sort, merge sort; NOT stable: quick sort [1]. Quick sort's partition step can move equal elements past each other in non-predictable ways, losing original ordering.
Q7Trace the bubble sort algorithm on the array [5, 3, 8, 1, 9] for ONE complete pass. Show the array state after each swap. State how many comparisons and how many swaps are made in this first pass.[5]
✅ Mark scheme
Compare 5,3 → swap → [3,5,8,1,9] [1]; Compare 5,8 → no swap [1]; Compare 8,1 → swap → [3,5,1,8,9] [1]; Compare 8,9 → no swap [1]; 4 comparisons made, 2 swaps made [1].
Q8Compare merge sort and insertion sort in terms of: (a) time complexity for best and worst case, (b) suitability for nearly-sorted data, (c) memory usage. Recommend which to use when sorting 100,000 random integers, justifying your answer.[6]
✅ Mark scheme
(a) Merge sort: O(n log n) best and worst; Insertion sort: O(n) best (nearly sorted), O(n²) worst [2]; (b) Insertion sort is highly efficient for nearly-sorted data; merge sort always O(n log n) regardless [1]; (c) Merge sort requires O(n) extra memory for merging; insertion sort is in-place O(1) extra space [1]; Recommendation: merge sort for 100,000 random integers [1]; justification: guaranteed O(n log n) performance avoids O(n²) worst case of insertion sort on large random data [1].
Topic Quiz
Question 1 of 10
You scored
out of 10
Card 1 of 8
Click to reveal definition
🎉
All cards reviewed!
TermDefinition
🎯

Mini Test — 4.4.1 Sorting

10 questions · 10 marks · 10 minutes

← 4.3.3 Trees & Hash Tables
75 of 82 · Cambridge 9618
4.4.2 Searching & Graph Algorithms →