Sub topic 4
Analyzing Loops and Nested Loops
Assume you know arrays, logarithms, summations, and basic asymptotic notation. Let \(n\) denote the input size. We count a dominant operation, such as a comparison or assignment, rather than every machine instruction.
Single and Nested Loops
A loop that advances by one usually runs \(n\) times:
total = 0
for i in range(n):
total += iThe body runs \(\Theta(n)\) times, so the time complexity is \(\Theta(n)\).
A loop that multiplies or divides its control variable changes differently:
i = 1
while i < n:
i *= 2The values are \(1, 2, 4, 8, \ldots\). After \(t\) iterations, \(i=2^t\). The loop stops when \(2^t \ge n\), so \(t \ge \log_2 n\). Its complexity is \(\Theta(\log n)\).
For nested loops, multiply iteration counts when the bounds are independent:
for i in range(n):
for j in range(n):
work(i, j)The inner operation runs \(n \times n\) times, giving \(\Theta(n^2)\). However, dependent bounds require a sum:
for i in range(n):
for j in range(i):
work(i, j)The total is
\[ 0+1+2+\cdots+(n-1)=\frac{n(n-1)}{2}=\Theta(n^2). \]
Sequential loops add their costs. The largest term dominates:
\[ \Theta(n)+\Theta(n^2)+\Theta(\log n)=\Theta(n^2). \]
| Loop pattern | Typical count |
|---|---|
| `i += 1` until \(n\) | \(\Theta(n)\) |
| `i *= 2` until \(n\) | \(\Theta(\log n)\) |
| Two independent \(n\)-loops nested | \(\Theta(n^2)\) |
| Inner loop runs to `i` | \(\Theta(n^2)\) |
Recurrences from Recursive Algorithms
A recurrence expresses the running time of a recursive algorithm in terms of smaller inputs. For example, a function that decreases its input by one has
\[ T(n)=T(n-1)+\Theta(1). \]
Expanding gives
\[ T(n)=T(n-2)+\Theta(1)+\Theta(1)=\Theta(n). \]
A divide-and-conquer algorithm that makes two half-sized calls and spends linear time combining results has
\[ T(n)=2T(n/2)+\Theta(n). \]
Substitution and Recursion Trees
Substitution repeatedly expands the recurrence:
\[ \begin{aligned} T(n)&=2T(n/2)+cn\\ &=4T(n/4)+2cn\\ &=8T(n/8)+3cn. \end{aligned} \]
At level \(j\), there are \(2^j\) subproblems of size \(n/2^j\). The total work at that level is
\[ 2^j \cdot c(n/2^j)=cn. \]
There are \(\log_2 n\) levels, so the total is \(\Theta(n\log n)\).
Exercise
What is the complexity of T(n) = T(n/2) + Θ(1), with T(1) = Θ(1)?
Show answer
Each level contributes Θ(1), and there are Θ(log n) levels, so T(n) = Θ(log n).