Sub topic 2
Counting Basic Operations Instead of Seconds
This chapter assumes you can read Python loops and conditionals, index into lists, and add up simple sums such as 1 + 2 + ... + n. It covers the cost model: the rule for deciding what we count when we measure an algorithm.
Why not measure seconds?
You could time a function with a stopwatch. The result would depend on the machine, the language, the other programs running, and the data you happened to pick. Two people running the same code would report different numbers.
Algorithm analysis wants a number that belongs to the algorithm itself. So we count basic operations, such as a comparison, an assignment, or an arithmetic step. Each one is assumed to take a constant amount of time. The count depends only on the algorithm and its input.
Choosing what to count
You do not have to count every operation. Pick the one that best reflects the work, usually the operation that runs most often inside the innermost loop. For searching and sorting, that operation is the comparison between two items.
This works because the other work, such as loop bookkeeping, grows in step with the comparisons. Counting comparisons alone gives the same growth pattern as counting everything.
A worked example
The function below finds the largest value in a list. It counts one comparison per item it checks.
def find_max(items):
comparisons = 0
best = items[0]
for x in items[1:]:
comparisons += 1
if x > best:
best = x
return best, comparisons
print(find_max([4, 8, 1]))
print(find_max([4, 8, 1, 9, 2, 6]))The output is (8, 2) and then (9, 5). A list of n items needs n - 1 comparisons, whatever the values are. The running time as a function of n is therefore T(n) = n - 1, and no stopwatch was needed.
Common errors
- Counting the wrong thing. If you count a step that runs only once, such as the initial assignment, you learn nothing about growth. Count what the loop repeats.
- Mixing units. Decide on one basic operation before you start. Counting comparisons in one place and swaps in another gives a meaningless total.
- Assuming the count is fixed.
find_maxalways does n - 1 comparisons, but many algorithms do not. A search can stop early, so its count depends on where the target sits. The next chapters build on this.
Exercise
A function loops over a list of n items and does one comparison per item, plus one extra comparison after the loop ends. What is T(n) if you count comparisons?
Show answer
T(n) = n + 1. The loop contributes n comparisons and the final check adds 1.