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.
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 aBubble 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.
- Compare
a[j]anda[j+1]. - Swap them if
a[j] > a[j+1]. - 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
| Case | Input | Comparisons (plain) | Comparisons (early exit) | Time |
|---|---|---|---|---|
| Best | sorted | with early exit | ||
| Average | random | close to | ||
| Worst | reverse sorted |
The plain version is 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 passes.
- Use a strict
>. With>=equal values swap and the sort is no longer stable.
Related
References
- 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.