Program Complexity
Compute T(α) by structural induction
Computing the complexity of a program requires structural induction on its
syntax. The rules mirror the structure of the language:
Base cases:
- Constants and variables: — they evaluate in one step.
Arithmetic operations: — per operation (one machine
instruction).
Function application: — cost of evaluating each
argument plus the function body.
Sequential composition :
The total is dominated by the slowest part.
Branching if P then alpha1 else alpha2:
Loops — for for i := 1 to n do alpha:
Recursion :
Set up a recurrence and solve it. Examples:
- Linear recursion .
- Binary recursion (divide & conquer) .
Examples:
- Linear search on a list of : .
- Binary search: .
- Selection sort: .
- Merge sort: .
To compute the time complexity of nested loops, count iterations.
Pattern 1: Single loop.
for i = 1 to n:
O(1) work
Total work: . Complexity: .
Pattern 2: Nested loops.
for i = 1 to n:
for j = 1 to n:
O(1) work
Total work: . Complexity: .
Pattern 3: Triangular nested loops.
for i = 1 to n:
for j = 1 to i:
O(1) work
Total work: . Complexity: (the leading term dominates).
Pattern 4: Loop with shrinking inner bound.
for i = 1 to n:
for j = 1 to n-i:
O(1) work
Total work: . Complexity: .
Pattern 5: Logarithmic inner loop.
for i = 1 to n:
j = 1
while j <= n:
j = j * 2
O(1) work
Inner loop runs times. Total: .
Reading. Each pattern reduces to a summation; identify the closed form; take the leading term. The summation is the most common.
for loop running times with body has total cost…