Skip to topic
    ← Back to course topics

    Bubble sort — AQA A-Level Computer Science

    Bubble sort is an elementary comparison-based sorting algorithm that repeatedly steps through a list, compares adjacent elements, and swaps them if they are in the wrong order. In AQA A-Level Computer Science, it serves as a foundational example of an in-place algorithm with O(n^2) worst-case time complexity and O(1) auxiliary space complexity.

    Bubble sort explained

    This statement requires you to know how bubble sort works, to trace its execution step by step on a small list, and to analyse its time complexity.

    Read the full explanation

    Bubble sort repeatedly passes through the list, comparing adjacent elements and swapping them when they are out of order, so that the largest unsorted value moves to the end on each pass. Tracing means recording the list after each comparison or pass, for example sorting [5, 3, 4] gives [3, 5, 4] after the first swap, then [3, 4, 5] after the second. Analysis examines how many comparisons are made as n grows. With n elements, the outer loop runs up to n−1 times and the inner comparisons shrink each pass, giving about n(n−1)/2 comparisons, so the worst-case and average-case time complexity is O(n²). The best case, where the list is already sorted and an early-exit flag stops the algorithm after one pass, is O(n).

    Your focus

    1. Know and be able to trace and analyse the time complexity of the bubble sort algorithm.

    Which command word is this?

    Follow the algorithm systematically step-by-step, recording variable states or array configurations at precisely specified intervals without skipping steps.

    Bubble sort exam tips

    Topic Overview

    Bubble sort is one of the standard sorting algorithms covered in the AQA A-Level Computer Science specification under algorithms and data structures. It functions by sequentially evaluating adjacent elements in an array or list, swapping their positions whenever they appear out of order until the entire structure is sorted.

    Understanding Bubble sort provides critical insight into time-space trade-offs, algorithm efficiency, and Big-O notation. It provides a baseline comparison against more advanced divide-and-conquer algorithms, such as Merge sort and Quick sort, which achieve better average-case runtime efficiency.

    Key Concepts
    • →Adjacent comparisons: The core mechanism of comparing item i with item i+1 and conditionally swapping them.
    • →Passes: A complete traversal of the unsorted segment of the list, at the end of which the largest remaining element bubbles to its final position.
    • →Optimization flag: A boolean variable (e.g., 'hasSwapped') that monitors whether any swaps occurred during a pass, permitting early exit in O(n) time.
    • →Time complexity bounds: Best-case O(n) with flag optimization, average-case O(n^2), and worst-case O(n^2).
    • →Space complexity: O(1) auxiliary space because it sorts in-place without generating copies of the list.
    Marking Points
    • Traces the algorithm by recording the list state after each swap or pass and identifies the element that is fixed at the end of each pass.
    • Explains that the inner loop length reduces by one on each pass, leading to roughly n(n−1)/2 comparisons.
    • States that the worst-case and average-case time complexity is O(n²).
    • Recognises that with an early-exit check on a sorted list the best case is O(n).
    Examiner Tips
    • 💡Write out the list after each pass when asked to trace, so each step can be followed and credited.
    • 💡Give the complexity for the case the question asks about, and say which case it is.
    • 💡Explain the shrinking inner loop when justifying an O(n²) result.
    • 💡Always state the array state after each full pass rather than after individual swaps unless the exam question explicitly asks for a step-by-step swap trace.
    • 💡If asked to write pseudocode, remember to reset your boolean swap flag to False at the start of every outer loop pass.
    • 💡When comparing sorting algorithms, highlight that Bubble sort's primary advantage is its low memory footprint and simplicity, while its main drawback is its quadratic time complexity on large datasets.
    Common Mistakes
    • Describes the number of passes as fixed at n; correct by noting the inner loop shortens after each pass, reducing the work.
    • Gives O(n) as the complexity for all cases; correct by stating that the worst case is O(n²) and O(n) applies only to the best case with early exit.
    • Traces the swaps without recording the list state, so the trace cannot be checked; correct by writing the full list after each pass or swap.
    • Believing that Bubble sort always takes the exact same number of passes regardless of initial ordering; in reality, an early-exit flag allows the algorithm to terminate after a single pass if the data is already sorted.
    • Confusing space complexity with time complexity, asserting that Bubble sort is memory-heavy; it is actually memory-efficient with O(1) auxiliary space.
    • Assuming Bubble sort compares elements across the entire array at arbitrary distances, confusing it with Insertion sort or Shell sort; it only ever compares strictly adjacent items.
    Revision Plan
    1. 1Day 1-2: Manually trace Bubble sort with paper and pen using an array of 5-6 values, noting element comparisons and swaps per pass.
    2. 2Day 3-4: Write and test the standard and optimized Bubble sort algorithms in Python or pseudocode using an early termination flag.
    3. 3Day 5-6: Derive the arithmetic progression formula (n(n-1)/2) to mathematically prove the O(n^2) worst-case time complexity.
    4. 4Day 7: Complete AQA past paper questions focusing on trace tables and algorithm comparisons against Merge sort and Insertion sort.
    Exam Question Types
    • 📋Trace tables and state outputs: Showing the array contents after each pass for a specific dataset.
    • 📋Pseudocode writing or completion: Implementing nested loops, swap mechanics, and early termination flags.
    • 📋Algorithm evaluation and comparison: Explaining when Bubble sort is suitable compared to Merge sort or Quick sort with reference to Big-O notation.
    Command Word Expectations (AQA)
    Trace

    Follow the algorithm systematically step-by-step, recording variable states or array configurations at precisely specified intervals without skipping steps.

    Explain

    Provide clear reasoning linking the mechanics of the algorithm (e.g., nested loops) directly to the resulting characteristic (e.g., O(n^2) time complexity).

    Compare

    Identify both similarities and differences between two algorithms (e.g., Bubble sort vs Merge sort), explicitly addressing time complexity, space complexity, and suitability.

    How Students Lose Marks (Examiner Pitfalls)
    Pitfall: Assuming the standard Bubble sort always takes O(n^2) time regardless of whether the list is already sorted.
    ❌ Weak Answer (Loses Marks):Bubble sort is always O(n^2) because it uses nested loops to compare every item with every other item.
    Example improved answer:In the worst and average cases, Bubble sort performs O(n^2) comparisons and swaps. However, if an early termination flag (e.g., 'swapped = False') is implemented, the best-case time complexity is O(n) when the list is already sorted, as the algorithm terminates after a single pass of (n - 1) comparisons.
    Examiner Tip: Always specify whether the algorithm uses an early-stopping boolean flag when discussing best-case time complexity in exam questions.
    Pitfall: Writing pseudocode that runs through the entire list without decreasing the inner loop upper bound on subsequent passes.
    ❌ Weak Answer (Loses Marks):for i = 0 to len(arr)-1: for j = 0 to len(arr)-2: if arr[j] > arr[j+1] swap
    Example improved answer:After pass i, the i largest elements are in their final positions at the end of the array. The inner loop should terminate at index (n - 1 - i) to avoid redundant comparisons on already sorted elements, though credit is awarded if an early exit check occurs when no swaps are made.
    Examiner Tip: When writing or tracing Bubble sort pseudocode, show that the comparison range reduces by one at the end of each pass.
    Step-by-Step Worked Solutions

    Question: Trace the execution of an optimized Bubble sort on the array [7, 3, 9, 2, 5]. Show the state of the array at the end of each complete outer pass, and state the total number of comparisons made.

    1. 1.Step 1: Identify initial state: [7, 3, 9, 2, 5], length n = 5.
    2. 2.Step 2: Pass 1 comparisons (4 comparisons total): - Compare 7 and 3: swap -> [3, 7, 9, 2, 5] - Compare 7 and 9: no swap -> [3, 7, 9, 2, 5] - Compare 9 and 2: swap -> [3, 7, 2, 9, 5] - Compare 9 and 5: swap -> [3, 7, 2, 5, 9] State after Pass 1: [3, 7, 2, 5, 9]. (Element 9 is in its final position).
    3. 3.Step 3: Pass 2 comparisons (3 comparisons total): - Compare 3 and 7: no swap -> [3, 7, 2, 5, 9] - Compare 7 and 2: swap -> [3, 2, 7, 5, 9] - Compare 7 and 5: swap -> [3, 2, 5, 7, 9] State after Pass 2: [3, 2, 5, 7, 9]. (Elements 7, 9 are in final positions).
    4. 4.Step 4: Pass 3 comparisons (2 comparisons total): - Compare 3 and 2: swap -> [2, 3, 5, 7, 9] - Compare 3 and 5: no swap -> [2, 3, 5, 7, 9] State after Pass 3: [2, 3, 5, 7, 9].
    5. 5.Step 5: Pass 4 comparison (1 comparison total): - Compare 2 and 3: no swap -> [2, 3, 5, 7, 9]. No swaps occurred during Pass 4, so the algorithm terminates.
    6. 6.Step 6: Calculate total comparisons: 4 + 3 + 2 + 1 = 10 comparisons.
    Final Answer: Pass 1: [3, 7, 2, 5, 9]; Pass 2: [3, 2, 5, 7, 9]; Pass 3: [2, 3, 5, 7, 9]; Pass 4: [2, 3, 5, 7, 9]. Total comparisons: 10.

    Question: Explain why Bubble sort has a worst-case time complexity of O(n^2) and an auxiliary space complexity of O(1).

    1. 1.Step 1: Define time complexity in terms of the number of operations relative to input size n. In the worst case (a reverse-ordered list), the algorithm must execute (n - 1) passes.
    2. 2.Step 2: Calculate the number of comparisons: Pass 1 requires (n - 1) comparisons, Pass 2 requires (n - 2), continuing down to 1 comparison on the final pass. The sum of integers from 1 to (n - 1) is (n(n - 1)) / 2 = (n^2 - n) / 2. In Big-O notation, lower-order terms and coefficients are ignored, yielding O(n^2).
    3. 3.Step 3: In this reverse-order scenario, every comparison also results in an element swap, leading to O(n^2) swaps.
    4. 4.Step 4: Define space complexity in terms of additional memory. Bubble sort sorts the list 'in-place', meaning it modifies the original array directly.
    5. 5.Step 5: Only a constant amount of temporary memory is required for loop index counters and the swap temporary variable, regardless of the size of n. Therefore, auxiliary space complexity is O(1).
    Final Answer: Worst-case time complexity is O(n^2) due to ((n^2 - n) / 2) comparisons and swaps; auxiliary space complexity is O(1) because sorting is performed in-place using a constant number of temporary variables.
    Active Recall Memory Test
    What is the worst-case and average-case time complexity of Bubble sort, and why?
    Key Fact: O(n^2), because it uses nested iterations that compare approximately n(n-1)/2 adjacent pairs in unsorted or reverse-sorted lists.
    What is the auxiliary space complexity of Bubble sort?
    Key Fact: O(1), because it operates in-place and only requires a constant amount of additional memory for temporary variables.
    Under what condition does Bubble sort achieve its best-case time complexity of O(n)?
    Key Fact: When the list is already sorted and an early termination check (swap flag) is implemented, exiting after 1 pass.
    After k passes of an ascending Bubble sort of n items, which elements are guaranteed to be in their final positions?
    Key Fact: The k largest elements are guaranteed to be in their final positions at the end of the list.
    Frequently Asked Questions
    Why is Bubble sort rarely used in real-world software?
    Bubble sort has an average and worst-case time complexity of O(n^2), making it extremely inefficient for large datasets compared to algorithms like Quick sort or Merge sort, which run in O(n log n) time. As the input size grows, the number of comparisons and swaps escalates quadratically. Its primary application is educational, helping students understand fundamental algorithmic concepts, loop mechanics, and complexity analysis.
    What is the purpose of the boolean swapped flag in Bubble sort?
    The swapped flag acts as an early termination mechanism. At the beginning of each pass, the flag is set to False, and it is only changed to True if an adjacent swap takes place. If a full pass completes and the flag remains False, the algorithm knows the list is completely ordered and stops immediately, reducing best-case time complexity to O(n).
    Is Bubble sort considered a stable sorting algorithm?
    Yes, Bubble sort is a stable algorithm when implemented correctly using strict inequality ('>' rather than '>='). Identical keys maintain their relative order because the algorithm only swaps adjacent elements when one is strictly greater than the other. This property is crucial in databases where multi-field sorting is required.
    How does Bubble sort differ from Insertion sort?
    While both algorithms share O(n^2) worst-case time complexity and O(1) space complexity, their mechanics differ substantially. Bubble sort works by repeatedly swapping adjacent items across the entire unsorted list until the largest values bubble to the end. In contrast, Insertion sort steps through the list one item at a time and inserts it into its correct position within an already sorted sub-list, typically making fewer swaps in practice.
    How many comparisons does Bubble sort make in the worst case for n items?
    In the worst case, an unoptimized Bubble sort without reduction of the inner loop range makes n * (n - 1) comparisons. An optimized Bubble sort that avoids checking already sorted elements at the end makes (n - 1) + (n - 2) + ... + 1 comparisons, which sums to n(n - 1) / 2 comparisons. For both variations, the resulting time complexity is O(n^2).