Bubble sort

Compare each pair of neighbours. Swap if they’re out of order. A swapped flag lets the sort stop early when a pass makes no changes.

Algorithms Beginner Sorting ~7 min
The idea

Largest values “bubble” up

Bubble sort repeatedly walks the list, swapping adjacent items that are in the wrong order. After one full pass, the largest unsorted value is in its final place.

Each pass starts with swapped = False. Any swap sets it to True. If a pass finishes with no swaps, the list is already sorted — break and skip the remaining passes.

TipWithout the flag, bubble sort always does O(n²) work. With it, nearly-sorted data can finish in roughly one pass.
IdeaEarly exit
bubble_sort.pyPython
for pass_i in range(n - 1):
    swapped = False
    for j in range(n - 1 - pass_i):
        if arr[j] > arr[j + 1]:
            arr[j], arr[j + 1] = arr[j + 1], arr[j]
            swapped = True
    if not swapped:
        break

Try both modes: unsorted and almost sorted.

Interactive

Run the simulation

Orange and blue bars are being compared. Green bars are in their final sorted positions. Watch the swapped box. The rows at the top are the array after each pass.

Step 0 / 0
demo.pyPython
Array + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember

What bubble sort teaches

Adjacent swaps, shrinking unsorted regions, and early exit.

Pass

One pass locks one item

After pass k, the last k items are sorted and never move again — unless you break early because nothing swapped.

swapped

No swaps → done

Reset swapped each pass. If it stays False, the array is sorted — break.

O(n²)

Best case becomes O(n)

Worst case is still quadratic, but already-sorted input finishes after one clean pass.