Sub topic 15
Counting Steps to Estimate Cost
This chapter assumes you can trace loops and nested loops with a trace table, and that you know the FindMax and InsertionSort procedures from earlier chapters. The goal here is to count how many times an algorithm does its main work and to write that count as a function of the input size n.
Pick a Basic Operation
Counting every assignment and every loop test by hand takes a long time and gives you little extra insight. Instead, choose one basic operation, the step that runs most often and drives the cost. For searching and sorting this is usually a comparison between elements or a move of an element.
| Algorithm | Basic operation | Why |
|---|---|---|
| FindMax | `A[i] > max` | Runs once per loop iteration |
| InsertionSort | Shift `A[i + 1] ← A[i]` | Runs inside the inner loop |
Counting a Single Loop
In FindMax, the loop FOR i ← 2 TO n runs n - 1 times. Each iteration makes one comparison, so the count is always n - 1, whatever the data. The assignment max ← A[i] depends on the data. A descending array triggers it 0 times and an ascending array triggers it n - 1 times.
Counting a Nested Loop
In InsertionSort, the number of inner-loop shifts depends on how far each key moves left. The worst case is a reversed array. There, each key moves past every element before it, so outer iteration j makes j - 1 shifts.
For n = 4 with input [4, 3, 2, 1]:
| j | key | shifts |
|---|---|---|
| 2 | 3 | 1 |
| 3 | 2 | 2 |
| 4 | 1 | 3 |
| total | 6 |
In general the worst case is 1 + 2 + ... + (n - 1) = n(n - 1)/2. The best case is a sorted array. There, the inner test A[i] > key fails immediately on every outer iteration, so the algorithm makes 0 shifts and n - 1 comparisons.
Checking Your Count with Code
You can confirm a hand count by adding a counter to a real implementation. This Python version uses 0-based indexing and counts shifts on reversed inputs:
def insertion_sort_shifts(a):
a = list(a)
shifts = 0
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i >= 0 and a[i] > key:
a[i + 1] = a[i]
i -= 1
shifts += 1
a[i + 1] = key
return a, shifts
for n in [4, 8, 16]:
worst = list(range(n, 0, -1))
_, s = insertion_sort_shifts(worst)
print(n, s, n * (n - 1) // 2)Each output line shows the measured count next to the formula: 4 6 6, 8 28 28, 16 120 120.
Common Errors
- Miscounting loop bounds.
FOR i ← 2 TO nrunsn - 1times, notntimes. This is the same off-by-one risk you meet in desk checking. - Multiplying nested loops blindly. The inner loop of insertion sort does not always run
ntimes. Sum the actual iterations for each value of the outer variable. - Reporting one case only. "Insertion sort makes
n(n - 1)/2shifts" is true only for the worst case.
Exercise
How many shifts does InsertionSort make on [2, 1, 4, 3], and how many does it make in the worst case for n = 10?
Show answer
On [2, 1, 4, 3] it makes 2 shifts: one when key 1 moves past 2, none for key 4, and one when key 3 moves past 4. The worst case for n = 10 is 10 × 9 / 2 = 45 shifts.
Exercise
How many times does FindMax evaluate A[i] > max on an array of 50 elements, and does the answer depend on the values?
Show answer
It evaluates the comparison 49 times (n - 1). The count does not depend on the values, because the loop always runs from 2 to n.