Bubble Sort Visualization: Step-by-Step Interactive Simulator

Bubble sort walks through the list comparing neighbours and swapping them when they are in the wrong order. After each pass the largest remaining item has bubbled to the end.

About this visualization

Bubble sort repeatedly compares neighbouring items and swaps them if they are in the wrong order, so the largest values bubble to the end of the list. It is slow on large inputs but perfect for learning how sorting works. Type your own numbers and watch every comparison and swap with live counters.

How it works

  1. Compare items i and i+1; swap if the left one is larger.
  2. After pass k, the last k items are in their final place.
  3. Stop early if a whole pass makes no swap — the list is sorted.

Worked example

Sort [5, 1, 4, 2]. Pass 1 compares (5,1) swap, (5,4) swap, (5,2) swap → [1, 4, 2, 5]. Pass 2 compares (1,4) fine, (4,2) swap → [1, 2, 4, 5]. Pass 3 finds nothing to swap, so it stops: 6 comparisons and 4 swaps in total.

Enter these numbers in the simulator above to see every step.

Complexity and properties

Best caseO(n)O(n)
Average caseO(n2)O(n^{2})
Worst caseO(n2)O(n^{2})
SpaceO(1)O(1)
StableYes
In-placeYes

Best case O(n)O(n) relies on the early-exit check.

When to use it

  • Learning the idea of swapping adjacent elements before moving to faster sorts.
  • Counting comparisons and swaps for homework.
  • Seeing the best case O(n)O(n) when the list is already sorted.

Frequently asked questions

What is the time complexity of bubble sort?

O(n2)O(n^{2}) in the average and worst case, and O(n)O(n) in the best case when the input is already sorted and the early-exit check is used. Space complexity is O(1)O(1).

Is bubble sort stable?

Yes. It only swaps adjacent items that are strictly out of order, so equal items keep their relative order.

Why is bubble sort rarely used in practice?

It makes many more comparisons and swaps than merge sort, quick sort or heap sort on large inputs.