BeginnerCoder

Lesson 5 — Bubble sort

Bubble sort: swap neighbours

Sorting puts items in order. Bubble sort walks through the list comparing each pair of neighbours; if they are in the wrong order, it swaps them. After one full pass the biggest value has "bubbled" to the end. Repeat until everything is in place. Python can swap two values in one line:

a, b = b, a
row[k], row[k + 2] = row[k + 2], row[k]   # swap two list items

Bubble sort is slow on big lists (O(n²) — double the list, four times the work) but very easy to understand.

Why it matters: it teaches the core sorting idea — compare and swap — used by every faster sort.

Want it another way?
Task

Write the swap line inside the if. Expected: [1, 2, 4, 5].

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.