Home › Theme B › B2 › B2.4 › B2.4.3

B2.4.3 Bubble sort and selection sort

SL + HLCommand terms: Construct, Trace, Evaluate

1. Sort visualiser

Choose an algorithm and a data set, then step through every comparison. Yellow: being compared. Red: swapped. Purple: current minimum (selection sort). Green: in its final place.

Algorithm: Bubble sortSelection sort   Data:
n = 10

2. Head-to-head on the same data

Both algorithms sort the same list. Who makes fewer comparisons? Who makes fewer swaps? Try each data set.

Data:  
Bubble sort
Selection sort
Choose a data set and press Race.

3. Experiment: how do they scale, and on what data?

Count the work for both algorithms on five kinds of data. Move n and watch the counts grow.

n = 100  

4. Trace it pass by pass

Write the list after each pass (the standard version, without early exit), as comma-separated numbers.

Algorithm: Bubble sortSelection sort   Start:

5. Flip-card deck

Click to flip. Say the answer before you flip.

6. Bubble, selection or both?

Which algorithm does each statement describe? Streaks of 3+ score double.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: after the pass

A new list each time. Which list results?

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 4, task 3. Binary search needs a sorted catalogue. Write both sorts with counters, compare them on sorted and reversed data, then use selection sort to rank books by number of copies, highest first.

Expected output

(9, 4) [1, 2, 4, 5, 8] (10, 2) [1, 2, 4, 5, 8] (4, 0) (10, 0) (10, 10) (10, 2) [['Kim', 7], ['Holes', 4], ['Dune', 2], ['Emma', 0]]

Evaluate

Use your output: (1) Why does bubble sort need only 4 comparisons on the sorted list, but selection sort still needs 10? (2) On the reversed list, why does selection sort make far fewer swaps? (3) ShelfWise adds a few new books to an already sorted catalogue each day. Which sort would you choose, and why? Would either be suitable for 100,000 books?

Check my code

    Next (B2.4.4, HL): recursion, and quicksort, an O(n log n) sort built with it. SL next: B2.5.1 saves the catalogue to a file.

    Practical tasks

    Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    Task 1: Bubble sort with a swap counter

    Write bubble_sort(items) that sorts a copy of the list in ascending order and returns (sorted_list, swaps). Try it on an already-sorted list and a reversed list.

    Starter file (write your code where it says pass # your code here):

    File: b2_4_3_average.py
    def bubble_sort(items):
        pass  # your code here
    
    # ---- tests ----
    print(bubble_sort([5, 1, 4, 2, 8]))
    print(bubble_sort([1, 2, 3, 4, 5]))
    print(bubble_sort([5, 4, 3, 2, 1]))
    

    Expected output when your code is correct:

    ([1, 2, 4, 5, 8], 4)
    ([1, 2, 3, 4, 5], 0)
    ([1, 2, 3, 4, 5], 10)
    Hint
    After each pass, the largest remaining value is in its final place, so the next pass can stop one earlier.
    Model solution
    File: b2_4_3_average_solution.py
    def bubble_sort(items):
        a = items[:]
        swaps = 0
        for end in range(len(a) - 1, 0, -1):
            for i in range(end):
                if a[i] > a[i + 1]:
                    a[i], a[i + 1] = a[i + 1], a[i]
                    swaps += 1
        return a, swaps
    
    # ---- tests ----
    print(bubble_sort([5, 1, 4, 2, 8]))
    print(bubble_sort([1, 2, 3, 4, 5]))
    print(bubble_sort([5, 4, 3, 2, 1]))
    
    Moderate

    Task 2: Selection sort, descending, with a trace

    Write selection_sort_desc(items) that sorts into descending order and prints the list after every pass. Then answer: how many passes and comparisons are needed for n items, and does it depend on the starting order?

    Starter file (write your code where it says pass # your code here):

    File: b2_4_3_moderate.py
    def selection_sort_desc(items):
        pass  # your code here
    
    # ---- tests ----
    print(selection_sort_desc([29, 72, 98, 13, 87]))
    

    Expected output when your code is correct:

    pass 1: [98, 72, 29, 13, 87]
    pass 2: [98, 87, 29, 13, 72]
    pass 3: [98, 87, 72, 13, 29]
    pass 4: [98, 87, 72, 29, 13]
    [98, 87, 72, 29, 13]
    Hint
    On each pass, find the position of the biggest remaining value and swap it to the front of the unsorted part.
    Model solution

    n − 1 passes and n(n − 1)/2 comparisons, whatever the starting order: selection sort always scans the whole unsorted part, so it is O(n²) in every case.

    File: b2_4_3_moderate_solution.py
    def selection_sort_desc(items):
        a = items[:]
        for i in range(len(a) - 1):
            biggest = i
            for j in range(i + 1, len(a)):
                if a[j] > a[biggest]:
                    biggest = j
            a[i], a[biggest] = a[biggest], a[i]
            print(f"pass {i + 1}: {a}")
        return a
    
    # ---- tests ----
    print(selection_sort_desc([29, 72, 98, 13, 87]))
    
    Challenging

    Task 3: Two-key bubble sort with early exit

    Sort students by grade (highest first), and alphabetically by name when grades are equal. Write sort_students(students) using a bubble sort with an early exit flag (stop when a pass makes no swaps). Return the sorted list and the number of passes. Check it matches sorted(students, key=lambda s: (-s[1], s[0])).

    Starter file (write your code where it says pass # your code here):

    File: b2_4_3_challenging.py
    def comes_before(a, b):
        pass  # your code here
    
    def sort_students(students):
        pass  # your code here
    
    # ---- tests ----
    s = [("Eli", 6), ("Ana", 7), ("Ben", 6), ("Cai", 5), ("Dev", 7)]
    result, passes = sort_students(s)
    print(result, passes)
    print(result == sorted(s, key=lambda x: (-x[1], x[0])))
    print(sort_students([("Ana", 7), ("Ben", 6)]))
    

    Expected output when your code is correct:

    [('Ana', 7), ('Dev', 7), ('Ben', 6), ('Eli', 6), ('Cai', 5)] 4
    True
    ([('Ana', 7), ('Ben', 6)], 1)
    Hint
    Write a helper that decides whether one student should come before another.
    Model solution
    File: b2_4_3_challenging_solution.py
    def comes_before(a, b):
        if a[1] != b[1]:
            return a[1] > b[1]
        return a[0] < b[0]
    
    def sort_students(students):
        a = students[:]
        passes = 0
        swapped = True
        while swapped:
            swapped = False
            passes += 1
            for i in range(len(a) - 1):
                if comes_before(a[i + 1], a[i]):
                    a[i], a[i + 1] = a[i + 1], a[i]
                    swapped = True
        return a, passes
    
    # ---- tests ----
    s = [("Eli", 6), ("Ana", 7), ("Ben", 6), ("Cai", 5), ("Dev", 7)]
    result, passes = sort_students(s)
    print(result, passes)
    print(result == sorted(s, key=lambda x: (-x[1], x[0])))
    print(sort_students([("Ana", 7), ("Ben", 6)]))
    

    Learning objectives

    By the end of this page you should be able to:

    1. Construct and trace bubble sort, including the optimised version that stops when a pass makes no swaps.
    2. Construct and trace selection sort.
    3. State and explain the time complexity of each (best, average and worst case) and their O(1) space complexity.
    4. Compare the numbers of comparisons and swaps each algorithm makes on different data sets: random, nearly sorted, sorted and reversed.
    5. Evaluate which algorithm, if either, suits a given data set and set of constraints.

    Bubble sort

    def bubble_sort(items):
        n = len(items)
        for i in range(n - 1):                 # pass number
            swapped = False
            for j in range(n - 1 - i):         # the last i items are already in place
                if items[j] > items[j + 1]:    # compare neighbours
                    items[j], items[j + 1] = items[j + 1], items[j]   # swap
                    swapped = True
            if not swapped:                    # optimisation: already sorted
                break

    Repeatedly compare adjacent pairs and swap them if they are in the wrong order. After pass 1 the largest item has "bubbled" to the end; after pass k, the last k items are in their final places.

    Selection sort

    def selection_sort(items):
        n = len(items)
        for i in range(n - 1):
            min_index = i
            for j in range(i + 1, n):          # find the smallest remaining item
                if items[j] < items[min_index]:
                    min_index = j
            if min_index != i:                 # at most one swap per pass
                items[i], items[min_index] = items[min_index], items[i]

    Find the smallest item in the unsorted part and swap it into the next position. After pass k, the first k items are the k smallest, in order.

    Complexity

    Bubble sort (with early exit)Selection sort
    Best case timeO(n): already sorted, one pass with no swapsO(n²): it always scans the whole unsorted part
    Average / worst case timeO(n²): up to n(n-1)/2 comparisons and swapsO(n²): always n(n-1)/2 comparisons
    SwapsUp to n(n-1)/2 (reversed data)At most n - 1
    SpaceO(1) extra: both sort in place, using only a few variables
    Stable?Yes: equal items keep their orderNo (the long-distance swap can reorder equal items)

    Advantages and disadvantages

    • Both: simple to write and verify; in-place (little memory); fine for small lists. But O(n²) scales badly: 100,000 books means about 5 × 10⁹ comparisons. Large data needs an O(n log n) sort such as merge sort or quicksort (B2.4.4).
    • Bubble sort is adaptive: on sorted or nearly sorted data it finishes very quickly. On random or reversed data it makes many swaps.
    • Selection sort makes very few swaps (writes), useful when writing is expensive (such as flash memory or moving heavy records), but it never benefits from data being already sorted.

    Java versions are identical in structure, using a temporary variable for the swap: int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp;

    Use the 中文 button at the top to show or hide the Chinese terms.

    Term中文Meaning

    Choose an answer. You get instant feedback.

    Score: 0 /

    Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

    1. Trace a bubble sort on [6, 2, 9, 4, 1], showing the list after each pass. [4]

    Pass 1: [2, 6, 4, 1, 9] [1]; pass 2: [2, 4, 1, 6, 9] [1]; pass 3: [2, 1, 4, 6, 9] [1]; pass 4: [1, 2, 4, 6, 9] [1].

    2. Construct a Python function selection_sort(items) that sorts a list into ascending order. [5]

    Outer loop over positions i from 0 to n - 2 [1]; set min_index = i [1]; inner loop from i + 1 to n - 1 [1]; update min_index when a smaller item is found [1]; swap items[i] and items[min_index] after the inner loop [1].

    3. State the worst-case time complexity and the space complexity of bubble sort and of selection sort. [2]

    Both O(n²) time in the worst case [1]; both O(1) extra space, as they sort in place [1].

    4. Explain why bubble sort with a "swapped" flag is efficient for data that is already nearly sorted. [3]

    The flag records whether any swap happened during a pass [1]; if a pass completes with no swaps, the list is sorted and the algorithm stops early [1]; nearly sorted data needs only a few passes, so the time approaches O(n) rather than O(n²) [1].

    5. A list of 8 items is in reverse order. Compare the number of swaps made by bubble sort and selection sort. [3]

    Bubble sort swaps every out-of-order adjacent pair: 8 × 7 / 2 = 28 swaps [1]. Selection sort makes at most one swap per pass, at most 7 (in fact 4 for reversed data, as each swap fixes two items) [1]. So selection sort is preferable when swaps/writes are expensive [1].

    6. ShelfWise must sort a catalogue of 100,000 books each night. Evaluate the use of bubble sort or selection sort for this task. [4]

    Both are O(n²): about n²/2 = 5 × 10⁹ comparisons, which is slow and scales badly as the catalogue grows [1]. Both are in-place, O(1) space, which is an advantage for memory [1]. If the catalogue is already nearly sorted (few new books each day), bubble sort with early exit approaches O(n) and could be acceptable [1]. Overall an O(n log n) algorithm such as merge sort or quicksort is more appropriate for this size [1].