Overview & Concept
Bubble Sort is an elementary comparison-based sorting algorithm. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. With each pass through the array, the next largest element "bubbles up" to its correct position at the end of the array.
How It Works
Adjacent Comparison: Compares neighboring pairs A[j] and A[j+1].
Conditional Swapping: If A[j] > A[j+1], values are swapped.
Pass Termination: Outer loop shrinks by 1 after each pass as the rightmost element settles.
Early Exit Optimization: If an entire pass completes with zero swaps, the array is already sorted and terminates in O(n) time.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(n) | O(n²) | O(n²) | O(1) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure bubbleSort(A):
n = length(A)
for i = 0 to n - 2:
swapped = false
for j = 0 to n - i - 2:
if A[j] > A[j + 1]:
swap(A[j], A[j + 1]); swapped = true
end for
mark A[n - 1 - i] as sorted
if not swapped: break
return A- Suffix Sortedness: After pass i, the last i elements are in their final sorted positions.
- Boundary Invariant: A[k] ≤ A[m] for all k < n - i and m ≥ n - i.
Advantages & Disadvantages
Key Advantages
- •Simple implementation and intuitive pedagogical mental model.
- •In-place sorting with O(1) auxiliary memory.
- •Stable: preserves the relative order of duplicate elements.
- •O(n) best-case performance on already-sorted inputs.
Trade-offs & Limitations
- •Poor O(n²) average and worst-case time complexity.
- •Excessive swap operations compared to Selection Sort or Insertion Sort.
Real-World Applications
Computer Science Education
Teaching fundamental concepts of sorting, loops, and algorithmic complexity.
Nearly-Sorted Micro Arrays
Checking whether a small dataset has been slightly disturbed.
Decision Guide: When to Use
Ideal Scenarios
- ✓When learning the basics of algorithms.
- ✓When arrays are very small (n < 10) or nearly sorted.
Consider Alternatives When
- ✕In any production codebase with large datasets (use Merge Sort or Quick Sort).
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.