Sub topic 1
Measuring Algorithm Cost: Input Size and Cases
Every later chapter in this tutorial compares algorithms by cost. This chapter defines what "cost" means and which input to measure it on.
Prerequisites
This chapter assumes you can do the following:
- Read and write loops, functions, and simple recursion.
- Index into arrays (lists).
- Use logarithms and exponents, and sum simple series such as 1 + 2 + ... + n = n(n+1)/2.
- Use modular arithmetic and basic counting.
Why measure cost abstractly
Wall-clock time depends on the machine, the language, the compiler, and what else is running. It tells you little about the algorithm itself. Algorithm analysis instead counts basic steps as a function of the input size. The result describes the algorithm and does not depend on the hardware.
Input size
The input size, usually written n, is the quantity that makes the problem larger. Choose it to match what the algorithm's work depends on:
| Problem | Natural input size n |
|---|---|
| Searching or sorting an array | Number of elements |
| Graph algorithms | Number of vertices and edges (V and E) |
| Matrix multiplication | Matrix dimension |
| Testing whether a number N is prime | Number of bits in N, which is about log N |
The last row is a common trap. A loop that runs N times is linear in the value N but exponential in the number of bits needed to write N. Unless a question says otherwise, GATE questions use the number of elements as n.
The cost model
We use the unit-cost model, also called the RAM model. Each of the following costs one step:
- An assignment
- An arithmetic operation
- A comparison
- An array access by index
Counting every step exactly is tedious and rarely useful. So we usually count one dominant operation, such as key comparisons in searching and sorting. This works because the other work in these algorithms is proportional to the dominant count. The notation chapter that follows makes this precise.
The unit-cost model has limits. It assumes numbers fit in a machine word. If the numbers can grow without bound, as in big-integer arithmetic, an addition costs time proportional to its digit count and the model no longer holds.
Best, worst, and average case
For a fixed n, different inputs can cost different amounts. We write T(n) for the cost and define three measures:
- Worst case: the maximum cost over all inputs of size n. It is an upper bound that holds for every input.
- Best case: the minimum cost over all inputs of size n. It is rarely informative alone.
- Average case: the expected cost under an assumed probability distribution over inputs of size n. The answer depends on that assumption.
Linear search shows all three. It scans an array from the left until it finds the key.
def linear_search(a, key):
"""Return (index, comparisons). Index is -1 if the key is absent."""
comparisons = 0
for i in range(len(a)):
comparisons += 1
if a[i] == key:
return i, comparisons
return -1, comparisons
n = 8
a = list(range(n))
costs = [linear_search(a, k)[1] for k in a]
print("best case (key at index 0):", min(costs))
print("worst case (key at last index):", max(costs))
print("average, key present and uniform:", sum(costs) / n)
print("unsuccessful search:", linear_search(a, 99)[1])The output is 1, 8, 4.5, and 8. In general:
- Best case: 1 comparison.
- Worst case: n comparisons. This happens when the key is last or absent.
- Average case, with the key present at each position with probability 1/n: (1 + 2 + ... + n) / n = (n + 1) / 2 comparisons.
If the key may also be absent, the average is higher. Suppose the key is present with probability p, and each position is equally likely given that it is present. The expected cost is p(n + 1)/2 + (1 − p)n. The answer changes with the assumption, which is why the assumption must be stated.
Worked analysis: counting a dominant operation
Consider finding the maximum of an array:
def find_max(a):
best = a[0]
for i in range(1, len(a)):
if a[i] > best:
best = a[i]
return bestThe loop makes exactly n − 1 comparisons for every input of size n. The best, worst, and average cases are all n − 1 comparisons. The number of assignments to best does vary. It is 0 for a descending array and n − 1 for an ascending array. So the case analysis depends on which operation you count, and you should say which one.
How the cases relate
Common errors
- Confusing the case with the bound. "Worst case" and "O" are different ideas. A case picks which inputs to consider. A bound, covered in the next chapter, describes how a function grows. You can state an upper bound on the best case, and a lower bound on the worst case.
- Assuming the average case is the middle of best and worst. For linear search it happens to be near n/2, but in general it must be computed from a distribution.
- Measuring one input and generalising. One timing run says nothing about the worst case.
- Taking n to be the numeric value. Check what the input size is for number-based problems.
- Ignoring the cost of the operation being counted. In a hash table, a "comparison" may itself involve comparing long strings.
GATE tips
- Read the question for the case asked: best, worst, or average.
- For "number of comparisons" questions, count only the comparisons between keys. Do not count loop-counter comparisons unless the question says to.
- If a question gives a probability that the key is absent, use the weighted formula shown above.
Exercise
A linear search runs on an array of n = 100 distinct elements. The key is present with probability 1/2. If it is present, it is equally likely to be at any position. If it is absent, the search compares against all elements. How many key comparisons are expected?
Show answer
Present case: (n + 1)/2 = 50.5 comparisons, with probability 1/2. Absent case: 100 comparisons, with probability 1/2. Expected cost = 0.5 × 50.5 + 0.5 × 100 = 25.25 + 50 = 75.25 comparisons.
Exercise
In find_max, how many comparisons of the form a[i] > best occur in the worst case for n elements, and does the best case differ?
Show answer
Exactly n − 1 comparisons in every case, because the loop runs from index 1 to n − 1 regardless of the values. The best case does not differ. Only the number of assignments to best varies.