Interactive demo

Bubble Sort Visualization

Bubble sort walks through the array again and again and swaps every pair of neighbors that is in the wrong order. It is simple, but with O(n²) steps one of the slowest sorting algorithms.

Your browser does not support the HTML5 canvas tag.

Choose “Sorted” as the starting order: a single pass without swaps is enough. “Reversed” is the worst case.

Playback

Comparisons
0
Writes
0

Array

Legend

  • Unsorted element
  • Compared neighbors
  • Final position

Runtime and properties

Best case

O(n)

Already sorted: one pass without a single swap ends the sort.

Average case

O(n²)

Every element moves only one place per swap, so about n²/2 comparisons are needed.

Worst case

O(n²)

Reversed order: every pass has to swap every pair it compares.

Extra memory

O(1)

Only neighbors are swapped, no extra memory is needed.

Stable

Yes

Equal neighbors are never swapped.

In-place

Yes

Elements are only swapped within the array.

n is the number of elements. O(n log n) is the best a sorting algorithm based on comparisons can achieve.

Compared with the other sorting algorithms

AlgorithmBest caseAverage caseWorst caseExtra memoryStableIn-place
Bubble sort this pageO(n)O(n²)O(n²)O(1)YesYes
Selection sortO(n²)O(n²)O(n²)O(1)NoYes
Insertion sortO(n)O(n²)O(n²)O(1)YesYes
Shell sortO(n log n)≈ O(n1.25)O(n1.5)O(1)NoYes
Tree sortO(n log n)O(n log n)O(n²)O(n)YesNo
Tournament sortO(n log n)O(n log n)O(n log n)O(n)YesNo
HeapsortO(n log n)O(n log n)O(n log n)O(1)NoYes
SmoothsortO(n)O(n log n)O(n log n)O(1)NoYes
Merge sortO(n log n)O(n log n)O(n log n)O(n)YesNo
Patience sortO(n)O(n log n)O(n log n)O(n)YesNo
TimsortO(n)O(n log n)O(n log n)O(n)YesNo
Block sortO(n)O(n log n)O(n log n)O(1)YesYes
QuicksortO(n log n)O(n log n)O(n²)O(log n)NoYes
IntrosortO(n log n)O(n log n)O(n log n)O(log n)NoYes
FluxsortO(n)O(n log n)O(n log n)O(n)YesNo
CrumsortO(n)O(n log n)O(n log n)O(log n)NoYes

1. Compare neighbors

A pass compares every element with its right neighbor. If the left one is larger, the two are swapped.

2. The largest bubbles up

The largest element is swapped along until it reaches the end of the array, like a bubble rising in water. After every pass the unsorted part is one element shorter.

3. Stop early

If a whole pass gets by without a single swap, everything is in order and the sort can stop. That makes bubble sort fast on arrays that are already sorted.