loop
Sorting lists: bubble sort

Module 3 · Sorting lists: bubble sort · Lesson 1 of 2

The bubble sort

Putting a list in order sounds simple — until you have to spell out exactly how. The bubble sort is the classic first algorithm: not the fastest, but wonderfully easy to follow. Its one idea is to repeatedly compare each pair of neighbours and swap them if they're in the wrong order.

Watch it work. Each pass walks left to right, comparing two bars at a time; whenever the left is taller than the right, they swap. The effect is that the largest value “bubbles” all the way to the end of each pass — so after every pass, one more value is locked in its final place.

Bubble sort, step by step
5
1
4
2
8

Notice the shape of it: an outer loop for the passes, an inner loop for the comparisons within a pass, and a single if that decides whether to swap. That's everything you learned in this module — loops, conditions and list indexing — working together. The swap itself uses a neat Python trick: a, b = b, a exchanges two values in one line.

Run it yourselfruns in your browser · Python
main.py

It works perfectly — and it's genuinely slow. For a big list, bubble sort does an enormous number of comparisons (roughly n × n), which is why nobody uses it for real work. It earns its keep as a teaching algorithm: simple enough to watch, and a perfect warm-up for the way you'll actually sort — which is next.