Bubble sort with early termination when no swaps occur, reducing unnecessary passes on nearly sorted data.
Optimized bubble sort improves the basic version by stopping early when the array becomes sorted. During a pass, if no swaps occur, the algorithm concludes that the sequence is already ordered and terminates.
This reduces unnecessary passes, especially for nearly sorted inputs.
Problem
Given a sequence of length , reorder it such that
Algorithm
Track whether any swap occurs during a pass. If a full pass completes without swaps, terminate.
optimized_bubble_sort(A):
n = length(A)
for i from 0 to n - 1:
swapped = false
for j from 0 to n - i - 2:
if A[j] > A[j + 1]:
swap(A[j], A[j + 1])
swapped = true
if swapped == false:
breakExample
Let
Pass 1:
| pair | action | result |
|---|---|---|
| (1,2) | keep | [1,2,3,5,4] |
| (2,3) | keep | [1,2,3,5,4] |
| (3,5) | keep | [1,2,3,5,4] |
| (5,4) | swap | [1,2,3,4,5] |
Pass 2:
No swaps occur, so the algorithm stops early.
Correctness
If a pass produces no swaps, then for all adjacent pairs:
which implies the entire sequence is sorted. Therefore termination is correct.
Complexity
| case | comparisons | time |
|---|---|---|
| best (already sorted) | ||
| worst | ||
| average |
Space complexity:
Properties
- stable
- in-place
- adaptive to nearly sorted input
When to Use
Use this variant when the input may already be sorted or close to sorted. It avoids redundant passes and improves practical performance compared to the basic version.
Implementation
def optimized_bubble_sort(a):
n = len(a)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return afunc OptimizedBubbleSort[T constraints.Ordered](a []T) {
n := len(a)
for i := 0; i < n; i++ {
swapped := false
for j := 0; j < n-i-1; j++ {
if a[j] > a[j+1] {
a[j], a[j+1] = a[j+1], a[j]
swapped = true
}
}
if !swapped {
break
}
}
}