Informal
Run-Time Analysis
Learn to count operations, recognize growth patterns, and classify algorithms using Big-O notation without formal proofs.
What Is Run-Time Analysis?
Run-time analysis answers a fundamental question: how does an algorithm's execution time grow as the input size increases? Instead of measuring wall-clock seconds (which vary by hardware), we count the number of key operations as a function of the input size \( n \).
Why Does Efficiency Matter?
Key Vocabulary
The Big-O Hierarchy
Core Rule: Drop Constants, Keep Dominant Term
When we write the Big-O for an algorithm, we follow two rules:
Loops Map to Big-O Classes
Sequential vs. Nested Loops
| Sequential (back-to-back) | Nested (inside each other) | |
|---|---|---|
| Structure | Loop 1 finishes, then Loop 2 starts | Loop 2 runs fully inside each iteration of Loop 1 |
| Operation Count | \( n + n = 2n \) | \( n \times n = n^2 \) |
| Big-O | \( O(n) \) | \( O(n^2) \) |
| Rule | Add the costs | Multiply the costs |
Step-by-Step Analysis
Example 1: Single Loop
Example 2: Nested Loops
Example 3: Halving Loop
If \( n = 16 \): the variable \( i \) takes values \( 16, 8, 4, 2 \): that's 4 iterations. Notice that \( \log_2 16 = 4 \).
Example 4: Tricky Nested Loop
The inner loop runs \( 0 \) times when \( i=0 \), then \( 1 \), \( 2 \), ... up to \( n-1 \). Total iterations:
Best, Worst, and Average Case
Common Mistakes
Run-Time Summary
| Code Pattern | Iterations | Big-O |
|---|---|---|
| No loop (fixed statements) | Constant | \( O(1) \) |
| Single loop: 1 to \( n \) | \( n \) | \( O(n) \) |
| Loop halving/doubling | \( \log n \) | \( O(\log n) \) |
| Two sequential loops | \( n + n \) | \( O(n) \) |
| Nested loops (both to \( n \)) | \( n \times n \) | \( O(n^2) \) |
| Loop inside halving loop | \( n \times \log n \) | \( O(n \log n) \) |
Question 1 of 5
for (int i = 0; i < n; i++) { process(arr[i]); } for (int j = 0; j < n; j++) { update(arr[j]); }
What is the Big-O run time of this code segment?
Question 2 of 5
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { compute(i, j); } }
What is the Big-O run time of this nested loop?
Question 3 of 5
int x = n; while (x > 1) { x = x / 2; }
How many times does the while loop execute when \( n = 64 \)?
Question 4 of 5
An algorithm has a statement execution count of \( 5n^2 + 3n + 100 \). What is its Big-O classification?
Question 5 of 5
for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { process(i, j); } }
What is the Big-O run time of this code segment?