Skip to main content
CodeFlow
all algorithms
algorithm 05

Bubble Sort

Walk the array. If two neighbours are out of order, swap them. Repeat. The biggest values bubble to the end one pass at a time — that's the whole algorithm.

05 / Bubble Sort

Adjacent swaps until sorted

42017188273355431596624761889
comparisons
0
result
step 0
  1. 0def bubble_sort(arr):
  2. 1 n = len(arr)
  3. 2 for i in range(n):
  4. 3 swapped = False
  5. 4 for j in range(0, n - i - 1):
  6. 5 if arr[j] > arr[j + 1]:
  7. 6 arr[j], arr[j + 1] = arr[j + 1], arr[j]
  8. 7 swapped = True
  9. 8 if not swapped:
  10. 9 break
Click Sort. Try the existing array, or shuffle for a fresh one.

What you just watched

Each pass walks the array once, comparing every adjacent pair. A pair that's out of order gets swapped. After pass 1, the largest value is guaranteed to be at the end — it bubbled all the way up. After pass 2, the two largest are at the end. And so on. The list is sorted after at most n passes.

Bubble sort is famously slow: O(n²) in the worst and average case. For 10 elements it's fine. For 10,000 it's painful. Smarter algorithms (merge sort, quicksort) hit O(n log n) by being clever about which comparisons to skip.

Try the Worst case button — it reverses the array so every comparison fires a swap. Then try Sort after a fresh shuffle and watch the early-exit kick in if the array happens to be nearly sorted.

The point of teaching bubble sort isn't to use it — most languages ship a much better sort built in. The point is that you can read the whole algorithm in five lines of code, watch each comparison happen, and feel why n × n comparisons gets expensive fast.