B2.4.3 · Sorting

Bubble sort

Python · step by step

Bubble sort

Watch the list change while following the actual Python execution.

Select Play or Next line to follow Python execution.

Python implementation

The highlight marks the next line to execute. Values show the state before that line.

def bubble_sort(items):    for end in range(len(items) - 1, 0, -1):        swapped = False        for j in range(end):            if items[j] > items[j + 1]:                items[j], items[j + 1] = items[j + 1], items[j]                swapped = True        if not swapped:            break    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 →

All practice & resources →