B2.4.3 Bubble sort and selection sort
SL + HLCommand terms: Construct, Trace, Evaluate1. 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.
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.
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.
4. Trace it pass by pass
Write the list after each pass (the standard version, without early exit), as comma-separated numbers.
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.
7. 45-second speed round: after the pass
A new list each time. Which list results?
Expected output
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
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.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
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):
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
Model solution
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]))
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):
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
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.
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]))
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):
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
Model solution
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:
- Construct and trace bubble sort, including the optimised version that stops when a pass makes no swaps.
- Construct and trace selection sort.
- State and explain the time complexity of each (best, average and worst case) and their O(1) space complexity.
- Compare the numbers of comparisons and swaps each algorithm makes on different data sets: random, nearly sorted, sorted and reversed.
- 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 time | O(n): already sorted, one pass with no swaps | O(n²): it always scans the whole unsorted part |
| Average / worst case time | O(n²): up to n(n-1)/2 comparisons and swaps | O(n²): always n(n-1)/2 comparisons |
| Swaps | Up to n(n-1)/2 (reversed data) | At most n - 1 |
| Space | O(1) extra: both sort in place, using only a few variables | |
| Stable? | Yes: equal items keep their order | No (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]
2. Construct a Python function selection_sort(items) that sorts a list into ascending order. [5]
3. State the worst-case time complexity and the space complexity of bubble sort and of selection sort. [2]
4. Explain why bubble sort with a "swapped" flag is efficient for data that is already nearly sorted. [3]
5. A list of 8 items is in reverse order. Compare the number of swaps made by bubble sort and selection sort. [3]
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]