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.
O(n²) work. With it, nearly-sorted data can finish in roughly one pass.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.
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.
What bubble sort teaches
Adjacent swaps, shrinking unsorted regions, and early exit.
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.
No swaps → done
Reset swapped each pass. If it stays False, the array is sorted — break.
Best case becomes O(n)
Worst case is still quadratic, but already-sorted input finishes after one clean pass.