Kids lining up by height

Bubble Sort

The analogy

Walk down a line of kids and only ever compare two side by side. If the left one is taller, they trade places. One full sweep pushes the tallest kid all the way to the back — like a bubble floating up. Sweep again and again until nobody needs to move.

Visualizer

Watch it sort

step 1 / 57
5
3
8
1
9
2
7
4

8 numbers, out of order. Press play — or step through one comparison at a time.

def bubble_sort(a):
    n = len(a)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        if not swapped:
            return a          # early exit -> O(n)
    return a
Check yourself

What does one full pass of bubble sort guarantee?