Sub topic 15
Counting Steps to Estimate Cost
A trace table tells you what an algorithm computes. With a small change, it can also tell you how much work the algorithm does. In this chapter you will count operations by hand, write the count as a formula in the input size n, and use that formula to predict how the algorithm behaves on inputs too large to trace.
This chapter assumes you can already trace loops and nested loops with a trace table, and that you know the FindMax and InsertionSort pseudocode from earlier chapters. You also need basic algebra, including the sum 1 + 2 + … + k = k(k + 1)/2.
Choosing What to Count
Counting every assignment, comparison, and index lookup is tedious, and it rarely changes the conclusion. Instead, pick one basic operation: the step that runs most often and that the algorithm's work depends on. Then count only that step.
| Algorithm | Good basic operation | Why |
|---|---|---|
| FindMax | The comparison `A[i] > max` | It runs once per loop iteration and decides the outcome |
| InsertionSort | The comparison `A[i] > key` | It sits in the innermost loop |
| Summing 1 to n | The addition `total + i` | It is the only work in the loop body |
| Searching for a value | The equality test against the target | Each test examines one element |
Counting a Single Loop
Here is FindMax again:
FUNCTION FindMax(A, n)
max ← A[1]
FOR i ← 2 TO n DO
IF A[i] > max THEN
max ← A[i]
END IF
END FOR
RETURN max
END FUNCTIONThe loop runs for i = 2, 3, …, n, which is n − 1 iterations. Each iteration performs exactly one comparison, so FindMax always performs n − 1 comparisons. The count doesn't depend on what is in the array. Whether the array is sorted, reversed, or random, the comparison count stays the same.
The assignment max ← A[i] behaves differently. It runs only when the condition is true. On [3, 7, 2, 9] it ran twice. On a sorted array it runs n − 1 times, and on an array whose first element is largest it never runs. When a count depends on the data, you need to be specific about which input you mean.
Counting Nested Loops with Sums
When one loop sits inside another, add up the inner loop's iterations over every value of the outer variable. Consider this loop, which compares every pair of elements:
count ← 0
FOR i ← 1 TO n DO
FOR j ← i + 1 TO n DO
IF A[i] = A[j] THEN
count ← count + 1
END IF
END FOR
END FOR
RETURN countFor a fixed i, the inner loop runs for j = i + 1 to n, which is n − i iterations. When i = n, the range i + 1 to n is empty, so the inner loop runs zero times. This follows the usual convention that a FOR loop whose start is past its end does nothing. Adding up over i:
(n − 1) + (n − 2) + … + 1 + 0 = n(n − 1)/2
For n = 4, that gives 3 + 2 + 1 + 0 = 6 comparisons, one for each of the six pairs.
A quick way to check a formula like this is to tabulate small cases by hand and compare:
| n | Inner iterations per i | Total | n(n − 1)/2 |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 2 | 1, 0 | 1 | 1 |
| 3 | 2, 1, 0 | 3 | 3 |
| 4 | 3, 2, 1, 0 | 6 | 6 |
Best Case and Worst Case: InsertionSort
PROCEDURE InsertionSort(A, n)
FOR j ← 2 TO n DO
key ← A[j]
i ← j - 1
WHILE i ≥ 1 AND A[i] > key DO
A[i + 1] ← A[i]
i ← i - 1
END WHILE
A[i + 1] ← key
END FOR
END PROCEDUREThe inner WHILE loop has no fixed iteration count. It stops either when A[i] > key is false or when i drops to 0. Because AND short-circuits, A[i] > key is not evaluated when i is 0. The count therefore depends on the data, and you analyze the extreme cases separately.
Worst case: reverse-sorted input. Every key is smaller than everything before it. For each j, the comparison is true j − 1 times, and then i reaches 0, so the loop stops without another comparison. Here is a trace of [4, 3, 2, 1] that counts comparisons:
Input: A = [4, 3, 2, 1], n = 4
j | key | comparisons made (A[i] > key) | count this j | running total | A after pass
---+-----+---------------------------------+--------------+---------------+-------------
2 | 3 | 4>3 T, then i=0 | 1 | 1 | [3,4,2,1]
3 | 2 | 4>2 T, 3>2 T, then i=0 | 2 | 3 | [2,3,4,1]
4 | 1 | 4>1 T, 3>1 T, 2>1 T, then i=0 | 3 | 6 | [1,2,3,4]The total is 1 + 2 + … + (n − 1) = n(n − 1)/2, which is 6 when n = 4.
Best case: already-sorted input. For each j, the first comparison A[j−1] > key is false, so the inner loop stops right away. That is one comparison per outer iteration, n − 1 in total, and no elements are shifted.
Average case. On random input, each key moves back about halfway, which gives roughly n²/4 comparisons. That is still quadratic, just with a smaller constant than the worst case.
Loops That Don't Count Up by One
If a loop variable is multiplied or divided at each step, the loop runs far fewer times than n:
steps ← 0
i ← 1
WHILE i ≤ n DO
steps ← steps + 1
i ← i × 2
END WHILE
RETURN stepsWith n = 8, i takes the values 1, 2, 4, and 8, so the body runs 4 times. In general it runs ⌊log₂ n⌋ + 1 times. Doubling n adds only one iteration. When you trace this kind of loop, record the value of i in each row, because the pattern of i values is the evidence for the logarithmic count.
From Counts to Growth
Exact formulas such as n − 1 and n(n − 1)/2 carry more detail than you usually need. For large n, the term with the highest power dominates and constant factors stop mattering for comparison. So n − 1 grows linearly and n(n − 1)/2 = n²/2 − n/2 grows quadratically. In Big-O notation those are O(n) and O(n²).
A practical consequence: if a quadratic algorithm takes 1 second on 10,000 items, expect about 4 seconds on 20,000 items. A linear algorithm would take about 2 seconds.
| Pattern in the pseudocode | Typical count | Growth |
|---|---|---|
| One loop, 1 to n | n | Linear |
| Loop that doubles or halves i | about log₂ n | Logarithmic |
| Two nested loops, each 1 to n | n² | Quadratic |
| Inner loop runs i + 1 to n | n(n − 1)/2 | Quadratic |
| Inner loop that may exit early | Different for best and worst case | Analyze each case |
Checking Your Count with Real Code
Once you have a formula, add a counter to a real implementation and compare the two. This Python version uses 0-based indexing and counts the comparisons a[i] > key:
def insertion_sort_count(values):
a = list(values)
comparisons = 0
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i >= 0:
comparisons += 1
if a[i] > key:
a[i + 1] = a[i]
i -= 1
else:
break
a[i + 1] = key
return a, comparisons
for n in range(1, 9):
_, worst = insertion_sort_count(list(range(n, 0, -1)))
_, best = insertion_sort_count(list(range(1, n + 1)))
print(n, best, n - 1 if n > 0 else 0, worst, n * (n - 1) // 2)Each printed row should show the best-case count equal to n − 1 and the worst-case count equal to n(n − 1)/2. If a row disagrees, either the code or your counting rule is off. For example, you may have counted the i >= 0 test as well. Because the comparison only happens when i >= 0 holds, the instrumented loop follows the same short-circuit rule as the pseudocode.
Exercise
How many times does the comparison A[i] > key run when InsertionSort sorts [2, 1, 3, 4]? Show the count for each value of j.
Show answer
For j = 2 (key 1), 2 > 1 is true and then i reaches 0, giving 1 comparison. For j = 3 (key 3), 2 > 3 is false, giving 1 comparison. For j = 4 (key 4), 3 > 4 is false, giving 1 comparison. The total is 3, the same as the best case for n = 4, because only one element is out of place and it moves just one position.
Exercise
Count, as a formula in n, how many times the innermost statement runs: FOR i ← 1 TO n DO, FOR j ← 1 TO i DO, x ← x + 1. Check your formula for n = 3.
Show answer
For each i, the inner loop runs i times, so the total is 1 + 2 + … + n = n(n + 1)/2. For n = 3 that is 1 + 2 + 3 = 6, which matches n(n + 1)/2 = 12/2 = 6. The growth is quadratic.
Exercise
A loop starts with i ← n and repeats WHILE i ≥ 1 DO with i ← i DIV 2 in the body (integer division). How many iterations does it run for n = 20, and how does the count grow?
Show answer
The values of i are 20, 10, 5, 2, 1, so there are 5 iterations, and then i becomes 0 and the loop stops. In general the count is ⌊log₂ n⌋ + 1, and ⌊log₂ 20⌋ + 1 = 4 + 1 = 5. The growth is logarithmic.