AP® Computer Science Principles · Big Idea 3 · Topic 3.9

Comparing Algorithms That Look Alike

Two algorithms that look almost identical can behave completely differently, so the way to compare them is to trace both step by step on the same input and watch where their values split apart.

A single changed symbol can change everything. A loop that initializes a total to 0 and one that initializes it to 1 look like the same algorithm with a typo, but they compute different things. The only reliable way to tell whether two algorithms actually do the same job is to run them side by side, in your head or on paper, on one shared input, and compare their variables after every step. If the traces ever disagree, in the final answer or anywhere along the way, the algorithms are not equivalent.

Tracing means writing down the value of every variable after each line executes, for both algorithms at once, using the same starting list or number. If one loop sums {2, 5, 3} by adding each element to a total that starts at 0, it ends at 10. The same loop starting its total at 1 ends at 11. Same structure, same list, different answer, because the one difference compounds through every iteration.

Matching final output is not the same as matching behavior. Two algorithms can also return the same value while one quietly does something extra, like modifying the original list, writing to a file, or changing a shared variable, while the other leaves everything untouched. That side effect matters even when the return value looks identical. This is why comparing algorithms connects to testing: one test case that happens to match tells you the two algorithms agree on that input, nothing more. A different list, especially an edge case like an empty list or a list with a negative number, can expose a difference that a single test never would.

Key terms

Trace
A step-by-step record of every variable's value as an algorithm executes.
Side effect
A change an algorithm makes beyond its return value, such as modifying a list or variable outside itself.
Equivalent algorithms
Algorithms that produce the same output for every possible input, not just one tested case.
Initial value
The starting value assigned to a variable before a loop begins changing it.

Watch it explained

  1. How it worksHow do you compare two algorithms by tracing both on one shared input side by side?
  2. Worked exampleTrace two loops that both sum a list, where one starts the total at 1 instead of 0.
  3. Going furtherWhat changes when two algorithms return the same result but one leaves a side effect behind?
  4. Common mistakeWhy isn't matching output on one test input proof that two algorithms are equivalent?

Check yourself

Your turn1 of 2
Two loops both sum a list of 15 numbers, but one of them starts its running total at 13 instead of 0. If the list's true sum is 467, what does the buggy loop return?

End of topic.