BeginnerCoder

Lesson 13 — Bubble sort with early exit

Stop early when nothing moves

Bubble sort from Lesson 5 always does every pass, even on a list that is already sorted. Smarter: keep a flag (a True/False variable) called swapped. If a whole pass makes no swaps, the list is sorted — break out early. Count the passes to see the difference.

changed = False
# ...set changed = True whenever something happens...
if not changed:
    break   # nothing happened this round, stop early

Why it matters: the best case drops from O(n²) to O(n). Spotting "we can stop now" is a key optimisation habit.

Want it another way?
Task

Remember that a swap happened, and stop early after a pass with no swaps. Already-sorted data should take 1 pass.

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.