B2.4.3 · Sorting
Bubble sort
Python · step by step
Bubble sort
Watch the list change while following the actual Python execution.
Python implementation
1def bubble_sort(items):2 for end in range(len(items) - 1, 0, -1):3 swapped = False4 for j in range(end):5 if items[j] > items[j + 1]:6 items[j], items[j + 1] = items[j + 1], items[j]7 swapped = True8 if not swapped:9 break10 return items The suffix beyond end is sorted. An early-exit flag gives O(n) best-case time; average and worst cases are O(n²). This in-place implementation uses O(1) auxiliary space.
Keep exploring
Return to the sorting lesson →
All B2.4 animations →