Algorithm Visualiser by Tsvetozar Biserov

Bubble Sort

  • Ω( n )
  • Θ( n2 )
  • O( n2 )
  • space O( 1 )

Bubble sort compares neighbours and swaps them when they are out of order, sweeping the array again and again until a sweep changes nothing. Each sweep drops the largest unplaced value into its final slot at the right end. This version shortens the sweep by one every time and stops early on a sweep without swaps, and it performs exactly one swap for every inversion in the input.

Array
Comparator strip Index down, time to the right
100 elements
×20 steps/frame

Comparisons 1
—
Reads 2
—
Writes 2
—
Swaps 3
—
Real time 4
—
Visual time 4
—
  1. Comparisons count only element-against-element checks; loop and index checks are never counted.
  2. Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
  3. A swap counts once, as a swap. It is never also counted as a read or a write.
  4. Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.

How bubble sort works

Take [5, 2, 6, 1, 4, 3]. The first sweep starts by swapping 5 and 2, giving [2, 5, 6, 1, 4, 3]. The pair 5 and 6 is in order, so the sweep moves on, but 6 is larger than 1, so the 6 starts to travel: [2, 5, 1, 6, 4, 3], then [2, 5, 1, 4, 6, 3], then [2, 5, 1, 4, 3, 6]. One sweep carried the 6 across three positions, and the last cell is now final.

Small values get no such ride. The 1 has moved from index 3 to index 2 and the second sweep lets it advance exactly one more place. That sweep swaps 5 with 1 to reach [2, 1, 5, 4, 3, 6], then pushes the 5 right through [2, 1, 4, 5, 3, 6] and [2, 1, 4, 3, 5, 6]. The third sweep swaps 2 with 1, giving [1, 2, 4, 3, 5, 6], and finally 4 with 3, which gives [1, 2, 3, 4, 5, 6].

The array is sorted after nine swaps, but the algorithm cannot tell yet. A fourth sweep over the first three cells makes two comparisons, finds nothing to swap and stops. The whole run costs 14 comparisons and 9 swaps, and 9 is also the number of inversions in the starting array: pairs such as (5, 2) or (6, 4) that stand in the wrong order. Each adjacent swap removes exactly one of them.

Bubble Sort on 5 2 6 1 4 3, one swap or write at a time. Indexes count from 0.
Step Change Array after
1 Swap indexes 0 and 1 2 5 6 1 4 3
2 Swap indexes 2 and 3 2 5 1 6 4 3
3 Swap indexes 3 and 4 2 5 1 4 6 3
4 Swap indexes 4 and 5 2 5 1 4 3 6
5 Swap indexes 1 and 2 2 1 5 4 3 6
6 Swap indexes 2 and 3 2 1 4 5 3 6
7 Swap indexes 3 and 4 2 1 4 3 5 6
8 Swap indexes 0 and 1 1 2 4 3 5 6
9 Swap indexes 2 and 3 1 2 3 4 5 6

All 9 changes are shown.

Pseudocode

for end = n - 1 down to 1
  swapped = false
  for i = 0 to end - 1
    if a[i + 1] < a[i]
      swap a[i], a[i + 1]
      swapped = true
  if not swapped
    stop

Why these complexities

Best case is linear. On sorted input the first sweep makes n-1 comparisons, sees no swap and breaks out, so the cost is n-1 comparisons and zero swaps. The flag that records whether a swap happened is what buys this, and it is also why bubble sort is adaptive: the closer the input is to sorted, the fewer sweeps it needs.

The worst case is a reversed array. Every pair is an inversion, so the sweeps cost n-1, n-2, ... down to 1 comparisons, which is n(n-1)/2 in total, and every comparison ends in a swap. On a random permutation about half of all pairs are inversions, so the swap count averages n(n-1)/4 and the comparison count lands only a little under n(n-1)/2, because the early exit rarely triggers before the last few sweeps. Both are O(n²).

How many sweeps are needed depends on one stubborn element: the value with the most larger elements in front of it. Every sweep moves such a value left by one place at most, so that count, plus one confirming sweep unless the count is already n-1, sets the number of passes. Memory is constant: the loop uses an end marker, an index and the swapped flag, and every exchange happens inside the array.

Measured on this site

Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.

Input Comparisons Writes Swaps
Random 496 0 311
Already sorted 31 0 0
Reversed 496 0 496
Few distinct values 391 0 169

When to use it

Use it to learn how sorting works, or on tiny arrays where simplicity matters more than speed. With the early exit it finishes in one pass on data that is already sorted. For anything bigger, insertion sort is just as simple and faster.

Frequently asked questions

Why is bubble sort slow?

Each pass moves only the largest remaining element to its place, and a small element near the end moves just one position per pass. That needs about n passes of up to n comparisons each, so O(n²).

Is bubble sort stable?

Yes. It swaps two neighbours only when the right one is strictly smaller, so equal elements never pass each other.

When does bubble sort run in linear time?

When the array is already sorted. The first pass finds no swap and the algorithm stops, after n-1 comparisons.

How many sweeps will bubble sort make on my data?

Look at each element and count the larger ones standing before it. A sweep reduces that count by one for every element where it is still positive, so the sweeps that change anything equal the largest count, and one more sweep confirms the result. In [5, 2, 6, 1, 4, 3] the values 1 and 3 each have three larger elements in front, so there are three working sweeps and a fourth that finds nothing.

Does remembering where the last swap happened help?

It can. Everything after the last swap of a sweep is already in its final place, so the next sweep may end there instead of one cell earlier. This implementation only shrinks the end by one, so it rescans a sorted tail on inputs like a sorted array with a few displaced values near the front. The worst case stays O(n²) either way.

Background

Nobody is known to have invented the method, and exchange sorting was already described in the 1950s. The name bubble sort appears in print in the early 1960s, and Knuth's survey of sorting by exchanging treats it at length before concluding that it has little to recommend it besides a catchy name.

Its lasting role is educational. It is short, its invariant is easy to state (after k sweeps the last k cells are final), and it is the usual first example for counting comparisons and for talking about stability. Practical code almost always uses insertion sort for small inputs and a divide-and-conquer sort for large ones.

References

  • Knuth, The Art of Computer Programming, vol. 3, section 5.2.2 (Sorting by Exchanging)
  • Knuth, The Art of Computer Programming, vol. 3, section 5.1.1 (Inversions)
  • Astrachan, Bubble Sort: An Archaeological Algorithmic Analysis, SIGCSE 2003

Compare with

Algorithm Average time Worst time
Cocktail Shaker Sort Θ( n2 ) O( n2 )
Comb Sort Θ( n2 ) O( n2 )
Gnome Sort Θ( n2 ) O( n2 )
Odd-Even Sort Θ( n2 ) O( n2 )
Quick Sort Θ( n log n ) O( n2 )
3-Way Quick Sort Θ( n log n ) O( n2 )
Dual-Pivot Quick Sort Θ( n log n ) O( n2 )
Big O notation
Best time Ω( n ) good
Average time Θ( n2 ) poor
Worst time O( n2 ) poor
Worst space O( 1 ) good

Properties

Stable
Yes
In place
Yes
Adaptive
Yes
Comparison-based
Yes