Step by step · Python, C++ and Java

Bubble sort, visualized step by step

Bubble sort walks the array again and again, swapping neighbours that are out of order, until everything is in place. It is the slowest sort you will meet in practice — and the easiest one to understand once you have watched it move.

How it works
arr = [5, 2, 9, 1, 7]
n = len(arr)

for i in range(n):
    for j in range(n - i - 1):
        if arr[j] > arr[j + 1]:
            arr[j], arr[j + 1] = arr[j + 1], arr[j]

print(arr)

How bubble sort works

Each pass compares every adjacent pair, arr[j] and arr[j + 1], and swaps them when the left one is larger. The largest value not yet in place is carried all the way to the end, like a bubble rising — so after pass i the last i elements are final, and the inner loop can stop i positions earlier.

The Python example sorts [5, 2, 9, 1, 7]. The outer loop counts passes; the inner loop’s range, n − i − 1, shrinks by one each time, which is the only optimisation this version makes.

What to watch for when it runs

  1. The two cells being compared light up on every step, and a swap animates them trading places.
  2. The sorted tail grows from the right by one cell per pass.
  3. The execution count on the comparison line climbs to n(n − 1) / 2 — that number is the O(n²).

Time and space complexity

Time
O(n²)
Space
O(1)

This version always makes n(n − 1) / 2 comparisons. Stopping early when a pass makes no swaps brings an already-sorted array down to O(n).

Stuck on your own version?

Paste it into the visualizer and watch your own code run, line by line — bugs included.