Algorithms · Visualized
Bubble Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Bubble Sort repeatedly walks through the array, comparing each pair of neighbouring elements and swapping them if they're in the wrong order. Time: O(n²) average, O(n²) worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Bubble Sort
SortingBubble Sort repeatedly walks through the array, comparing each pair of neighbouring elements and swapping them if they're in the wrong order. After each full pass, the largest remaining unsorted element 'bubbles up' to its correct position at the end, just like a bubble rising to the surface of water.
How Bubble Sort Works
- Start at the beginning of the array.
- Compare each pair of adjacent elements.
- If the left element is bigger than the right one, swap them.
- Move to the next pair and repeat until you reach the end of the array — this is one full pass.
- After each pass, the largest unsorted element is now in its final position, so you can ignore it in future passes.
- Repeat the passes until a full pass happens with no swaps — the array is sorted.
Bubble Sort Worked Example
Input: [5, 1, 4, 2, 8]
Pass 1: compare 5&1 → swap → [1,5,4,2,8]; compare 5&4 → swap → [1,4,5,2,8]; compare 5&2 → swap → [1,4,2,5,8]; compare 5&8 → no swap. Largest value 8 is now fixed at the end. Pass 2: [1,4,2,5,8] → swaps bring it to [1,2,4,5,8]. Pass 3: no swaps needed — array is sorted: [1,2,4,5,8].
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:
break
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Bubble Sort Time & Space Complexity
When to Use Bubble Sort
- Teaching the idea of comparison-based sorting to beginners.
- Very small datasets where simplicity matters more than speed.
- Detecting whether a list is already nearly sorted (few swaps needed).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.