Developer Toolbox

Bubble sort

Goes through the list again and again and swaps neighbours that are in the wrong order. After each pass, the largest remaining value is at the end.

  • Ω(n)
  • Θ(n²)
  • O(n²)
  • O(1)
  • yes
  • yes
  • comparing
  • moving
  • in final place
0 / 453 steps

Pairs out of order: 154 (at the start: 154) out of order put in order

Comparisons Swaps

Press play: the lines show how the cost grows as the sort runs

Press play or step through the algorithm.

Space: play or pause. Left and right arrows: step. Home and End: jump.

Try this: Pick a nearly sorted list. After one pass with no swaps, the algorithm stops early.

How it works

It compares two neighbours at a time and swaps them if the left one is bigger. So in each pass the biggest value moves all the way to the right, like a bubble rising. If a pass makes no swaps, the list is already sorted.

When it is a good choice

Almost never in real programs, because it is slow on long lists. It is great for learning: it shows the basic idea of sorting by comparing and swapping. It is fast only when the list is already sorted.