What is Big-O Notation & Algorithm Complexity Analysis?
Mathematical Foundation
Laws & Principles
- Complexity hierarchy (slowest to fastest growth): O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(n³) < O(2ⁿ) < O(n!). For n = 1,000, O(n!) produces 10²567 operations — more than atoms in the observable universe.
- Drop lower-order terms and constants: O(3n² + 5n + 7) = O(n²). The constant 3 and lower terms are irrelevant for asymptotic analysis. Only the fastest-growing term determines the class.
- Space complexity uses the same Big-O notation but measures memory usage, not time. An in-place sort (O(1) space) vs merge sort (O(n) space) can be a critical distinction for embedded systems.
- Best-case (Omega Ω), worst-case (O), and average-case (Theta θ) can all differ for the same algorithm. Quicksort: O(n log n) average, O(n²) worst case. Always consider the worst case for safety-critical software.
Step-by-Step Example Walkthrough
" Compare Bubble Sort O(n²) vs Merge Sort O(n log n) on a 1,000,000-element array, assuming 10⁹ operations per second (modern CPU). "
- Bubble Sort operations: n² = (10⁶)² = 10¹² operations
- Bubble Sort time: 10¹² / 10⁹ = 10³ seconds = ~16.7 minutes
- Merge Sort operations: n log₂n = 10⁶ × log₂(10⁶) = 10⁶ × 19.93 ≈ 1.99 × 10⁷ operations
- Merge Sort time: 1.99 × 10⁷ / 10⁹ = 0.0199 seconds ≈ 20 milliseconds