/utils

Bubble Sort

Compare neighbours and swap them when they are out of order. Each pass bubbles the largest value to the end. Simple to teach, rarely the right choice.

SolvesSorting

best
O(n)
average
O(n^2)
worst
O(n^2)
space
O(1)

Bubble sort walks along the array and swaps every neighbouring pair that is out of order. The largest value rises to the end like a bubble. Then the walk repeats on the shorter rest.

Already sorted: no pair is out of order, so there are no swaps. The early-exit version stops after one pass with n − 1 comparisons. The plain version still makes n(n − 1)/2.

1021324354657687end
1def bubble_sort(a):2    n = len(a)3    for end in range(n - 1, 0, -1):4        # largest of a[0..end] moves to a[end]5        for j in range(end):6            if a[j] > a[j + 1]:7                a[j], a[j + 1] = a[j + 1], a[j]8    return a
1 / 36

Bubble the largest of a[0..7] up to index 7.

comparisons
0
swaps
0

How it works

After pass k, the k largest values sit at the end in their final places. So pass k + 1 needs to look at a[0..n-k) only.

  1. Compare a[j] and a[j+1].
  2. Swap them if a[j] > a[j+1].
  3. Move to j + 1. At the end of the range, shrink the range by one and start again.

Each swap removes exactly one inversion. So the number of swaps equals the number of inversions of the input [1].

Complexity

CaseInputComparisons (plain)Comparisons (early exit)Time
Bestsortedn(n−1)2\frac{n(n-1)}{2}n−1n - 1O(n)O(n) with early exit
Averagerandomn(n−1)2\frac{n(n-1)}{2}close to n(n−1)2\frac{n(n-1)}{2}O(n2)O(n^2)
Worstreverse sortedn(n−1)2\frac{n(n-1)}{2}n(n−1)2\frac{n(n-1)}{2}O(n2)O(n^2)

The plain version is O(n2)O(n^2) in every case. The early-exit version is adaptive: it needs one pass on sorted input.

Implementations

  • Plain: every pass runs, even when nothing moves.
  • Early exit: tracks whether a pass swapped anything and stops when it did not.

Pitfalls

  • Small values move left by only one slot per pass. A single small value at the far end makes the sort take n−1n - 1 passes.
  • Use a strict >. With >= equal values swap and the sort is no longer stable.

Related

References

  1. T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.

Further reading

  • D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.

Full bibliography