Short answer: Bubble sort swaps every adjacent inversion and then shortens the unsorted prefix. After pass i the last i items are in their final places. A pass that swaps nothing means the prefix is sorted too, so the scan stops. The worst case remains Θ(n²) comparisons. It is a stable in-place sort for a short list, and a demonstration of how slowly adjacent swaps remove inversions.
What the problem actually asks
The input is a sequence under a total order. An adjacent swap fixes one neighboring inversion and can move an item only one slot closer to its destination. The useful question is which prefix is still unknown after each pass, and which observation proves that the unknown prefix has shrunk to nothing.
Stability means equal keys keep their original order. That holds when the comparison that swaps is strict: a lesser neighbor is swapped, and an equal neighbor is left where it is.
What the algorithm guarantees
Pass i bubbles the maximum of the still-unsorted prefix into index n−1−i. Those finished suffix items are never touched again. If a full pass performs no swap, the prefix has no adjacent inversion. A total order with no adjacent inversion is sorted, so the early exit is exact. Extra memory is a handful of indices.
The best case, an array that is already sorted, is Θ(n): one pass, zero swaps. The worst case, a reversed array, is Θ(n²) comparisons and Θ(n²) swaps. The average over random permutations is also Θ(n²), because a random permutation has Θ(n²) inversions and each swap removes only one.
The working steps
- Set the unsorted length to n.
- Scan adjacent pairs inside that length. A pair out of order is swapped, and the pass is marked dirty.
- If the pass was clean, return. The array is sorted.
- Otherwise decrease the unsorted length by one. The item that reached the end of the scan stays there.
- Repeat until the unsorted length is 1.
The accounting is for a comparison sort that may examine every adjacent pair. A nearly sorted file whose disorder is a few long-range swaps still pays a quadratic scan. Algorithms that move an item farther than one slot in one step are a different family.
Approaches that look simpler and fail
| Approach | Why it fails when adjacent swaps are the only move |
|---|---|
| One forward pass | Each item moves at most one slot left. A minimum parked at the last index needs n−1 passes to reach the front. |
| A fixed cap on the number of passes | The inversion count depends on the input. A cap chosen in advance leaves a long inversion untouched. |
| Swap when the comparison is greater-or-equal | Equal keys change order. The sort stops being stable. |
| Quote the best-case linear scan as the cost | That scan is the already-sorted input. A random permutation still has Θ(n²) inversions. |
Adjacent swaps are the right picture when the goal is to count inversions one by one. A sort that has to scale uses a merge, a heap, or a hybrid such as timsort or introsort.
A working example
The Bash script and the Python script bubble-sort the same integers. Each pass fixes one more suffix item. Both print 1 2 2 3 4.
a=(4 2 2 3 1)
n=${#a[@]}
for ((i=0; i<n-1; i++)); do
for ((j=0; j<n-1-i; j++)); do
if (( a[j] > a[j+1] )); then
t=${a[j]}
a[j]=${a[j+1]}
a[j+1]=$t
fi
done
done
echo "${a[*]}"
a = [4, 2, 2, 3, 1]
n = len(a)
for i in range(n - 1):
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
assert a == sorted(a)
print(*a)
Where it is used
Bubble sort is not the sort in any current standard library. The one idea that survives is the early exit when a pass swaps nothing, and only on a tiny nearly sorted array. Timsort and introsort are what languages actually call.
When you can drop this algorithm
Drop bubble sort once n leaves the range where a quadratic term is invisible, and whenever the input is not already almost ordered. Insertion sort has the same worst case, a better constant, and the same early exit on sorted data, and it is the usual small-array base case. Keep bubble sort when a stable adjacent-swap procedure is wanted and each pass must leave a finished, ordered suffix.
Why this stays published
We publish this so a search for bubble sort returns the finished suffix, the swap-free exit, and the quadratic cost that still applies to a random permutation. Bubble sort places one suffix item per pass and may stop after a clean pass, and a random input still costs a quadratic number of adjacent swaps.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
