Bubble Sort iterates through the list, comparing adjacent elements $(lst[j], lst[j+1])$ and swapping them if they are in the wrong order ($lst[j] > lst[j+1]$). At the end of Pass 1, the largest element has "bubbled up" to the final index $n-1$. Pass 2 bubbles the second-largest element to index $n-2$, and so forth.
Optimized Bubble Sort Implementation in Python:
def bubble_sort(lst):
n = len(lst)
for i in range(n - 1):
swapped = False # Optimization flag: detects early sorted state!
for j in range(n - 1 - i):
if lst[j] > lst[j + 1]:
# Swap adjacent elements:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
swapped = True
print(f"Pass {i + 1}: {lst}")
if not swapped:
# If no swaps occurred in this pass, array is ALREADY SORTED!
print("Early termination: Array sorted!")
break
return lst
Complexity:
- Total Comparisons (unoptimized): $(n-1) + (n-2) + \dots + 1 = \frac{n(n-1)}{2} = O(n^2)$.
- Best-case Time (Optimized): $O(n)$ when list is already sorted (terminates after Pass 1).
- Worst-case Time: $O(n^2)$ when list is in reverse sorted order.
- Space Complexity: $O(1)$ in-place auxiliary space. Stability: Stable.