GCSE Python · Lesson 4 of 9

Bubble sort and trace tables

OCR J277 2.1 / AQA 8525 algorithms

Swap adjacent out-of-order items and record the result of each pass.

← All GCSE Python lessons

Sorting with bubble sort

Bubble sort compares neighbouring values, swapping those that are out of order. After each full pass the largest remaining item moves towards its final position. Record the list after each comparison to see how the algorithm progresses.

Watch out: Do not use Python sort() in an exercise that asks you to implement the algorithm yourself.

1 · Learn and predict

Read this worked example. Predict its output, run it in Python 3, and explain how variables change.

values = [5, 2, 4, 1]
for end in range(len(values)-1, 0, -1):
    for i in range(end):
        if values[i] > values[i+1]:
            values[i], values[i+1] = values[i+1], values[i]
    print(values)

2 · Build independently

Swap adjacent out-of-order items and record the result of each pass. Work from the starter code before comparing with the solution.

Download starter + solution ZIP ↓

For a stretch challenge: add meaningful test data, handle an edge case and explain one design decision.

Reveal reference solution
def bubble_sort(values):
    data = values.copy()
    for end in range(len(data)-1, 0, -1):
        swapped = False
        for i in range(end):
            if data[i] > data[i+1]:
                data[i], data[i+1] = data[i+1], data[i]
                swapped = True
        if not swapped:
            break
    return data

for data in ([5,2,4,1], [1,2,3], []):
    print(data, '->', bubble_sort(data))

The reference is one possible approach. Test your own program before comparing.

3 · Debug and explain

Question: Why is the inner loop bound reduced after each pass?

Show explanation

After each complete pass, the largest remaining value is in its final position.

4 · Check your understanding

After one full ascending bubble-sort pass, which is guaranteed?

5 · Reflect

Explain one test you used, one problem you solved and one improvement you would make.

This records completion only in this browser and does not certify mastery.

Want extra practice? Try interactive Python tracing and debugging questions →