Skip to content

9618 · 19.1

Algorithms — practice questions

Practice and worked examples for 9618 Algorithms. Short previews only — attempt the full question in MarkScheme against the official scheme.

Worked example 1

An integer array Data is sorted in ascending order: [3, 5, 8, 11, 15, 22, 29, 31]. Trace the execution of a binary search to find the value 22. The array has indices 0 to 7. Use Low, High, and Mid=(Low+High)//2Mid = (Low + High) // 2 (integer division).

Show solution outline

Target Value: 22 Initial state: Low=0Low = 0, High=7High = 7

Pass 1:

  • Mid=(0+7)//2=3Mid = (0 + 7) // 2 = 3
  • Data[Mid] is Data[3], which is 11.
  • 11<2211 < 22, so the target is in the upper half.
  • New state: Low=Mid+1=4Low = Mid + 1 = 4, High=7High = 7

Pass 2:

  • Mid=(4+7)//2=5Mid = (4 + 7) // 2 = 5
  • Data[Mid] is Data[5], which is 22.
  • 22==2222 == 22. The value is found at index 5.

Result: Value 22 found at index 5.

Worked example 2

Trace the Bubble Sort algorithm on the array [7, 2, 8, 5]. Show the state of the array after each complete pass.

Show solution outline

Initial Array: [7, 2, 8, 5]

Pass 1:

  • Compare 7 and 2: Swap. Array: [2, 7, 8, 5]
  • Compare 7 and 8: No swap. Array: [2, 7, 8, 5]
  • Compare 8 and 5: Swap. Array: [2, 7, 5, 8]
  • End of Pass 1: [2, 7, 5, 8] (The largest element, 8, is now in its final position).

Pass 2:

  • Compare 2 and 7: No swap. Array: [2, 7, 5, 8]
  • Compare 7 and 5: Swap. Array: [2, 5, 7, 8]
  • (No need to compare with 8 as it's already sorted).
  • End of Pass 2: [2, 5, 7, 8] (The second largest element, 7, is now in position).

Pass 3:

  • Compare 2 and 5: No swap. Array: [2, 5, 7, 8]
  • (No need to compare with 7 and 8).
  • End of Pass 3: [2, 5, 7, 8]

Since no swaps occurred in Pass 3 (if using an optimised version with a flag), the algorithm would terminate. The final sorted array is [2, 5, 7, 8].