Bubble Sort
Overview
Bubble sort works by iterating downward through an array, swapping larger elements upward as needed.
| Property | Value |
|---|---|
| Best Case | |
| Worst Case | |
| Avg. Case | |
| Aux. Memory | |
| Stable | Yes |
| Adaptive | Yes |
| Visualization | ![]() |
Loop Invariant
Bubble sort has loop invariant
A[0:i-1]is a sorted array of theileast elements ofA.
- Initialization
- When
i = 0,A[0:-1]is an empty array. This trivially satisfies.
- When
- Maintenance
- Suppose
holds for some 0 ≤ i < n - 1. ThenA[0:i-1]is a sorted array of theileast elements ofA. Our inner loop now starts at the end of the array and swaps each adjacent pair, putting the smaller of the two closer to positioni. Repeating this process across all pairs fromn - 1toi + 1ensuresA[i]is the smallest element ofA[i:n-1]. ThereforeA[0:i]is a sorted array of thei + 1least elements ofA. At the end of the iteration,iis incremented meaningA[0:i-1]still satisfies.
- Suppose
- Termination
- Termination happens when
i = n - 1. Thenimplies A[0:n-2]is a sorted array of then - 1least elements ofA. But thenA[n-1]must be the greatest element ofAmeaningA[0:n-1], the entire array, is in sorted order.
- Termination happens when
