Start from foundations · Course contents · فارسی
Next lesson: Cost analysis from scratch: counting work and time growth
From problem to algorithm: data, tracing and a first cost analysis
Four cards contain 4, 9, 2 and 7. Which number is largest? You might answer at a glance, but a computer needs a definite procedure that also handles forty or one thousand cards.
This is the first lesson of DS-01 — Cost analysis. No C syntax or complexity notation is assumed. The goal is to execute a method, explain correctness and count comparisons. An available introductory lesson does not mean the whole chapter is complete or that you have mastered it.
1. A problem differs from one instance
“Find the largest number in a list” is a problem. 4, 9, 2, 7 is one instance. An algorithm must handle all allowed instances, not only its demonstration.
Here input is a finite nonempty list of comparable numbers, possibly negative or repeated. Output is the maximum value, not its position. An empty list has no maximum under this contract: report emptiness rather than inventing zero.
Input is the data received; output is the required result. Specifying both first prevents solving the wrong problem.
2. An algorithm gives executable instructions
An algorithm is a precise, terminating sequence of steps for solving a problem. “Find the big number” does not explain the steps: specify what to compare and what to do afterward.
Keep a value named best, meaning “largest seen so far.” This is a variable, a named place holding a value in this explanation. The name stays fixed while its stored value may change.
In the pseudocode, ← assigns a new value; it is not a permanent mathematical equality. This is not C and requires no C grammar.
If the list is empty, report "no maximum" and stop.
best ← first number
For each remaining number, in order:
If that number is greater than best:
best ← that number
Report best at the end.
The first number is a temporary answer because it is the only number examined initially, not because we already know it is globally largest.
3. Trace the changing state
Execute on 4, 9, 2, 7:
| Stage | New number | Comparison | best afterward |
|---|---|---|---|
| Initialization | 4 | None yet | 4 |
| 1 | 9 | 9 > 4, true | 9 |
| 2 | 2 | 2 > 9, false | 9 |
| 3 | 7 | 7 > 9, false | 9 |
A trace records the procedure's state after each step. Merely writing nine does not show why it works or what another instance will do.
For −8, −3, −11, initializing from the first entry gives minus eight, then minus three, then minus three. Starting at zero would fail: no entry exceeds it, and the output would not even belong to the list.
4. Why is it correct for every allowed input?
Preserve the statement: after each stage, best is the maximum of the examined prefix.
- Initially only the first entry was examined; it is that one-entry prefix's maximum.
- Suppose the statement holds before a new entry. If the entry exceeds best, replacing best gives the new maximum; otherwise the old maximum remains correct.
- The finite list loses one unexamined entry each stage, so the procedure terminates. The examined prefix is then the entire list and best is the overall maximum.
Such a preserved statement is an invariant. The important skill is explaining what remains true after the next step, not memorizing its name.
Several successful examples are not the same as correctness reasoning. Examples can expose bugs; the argument explains why each step preserves the needed property.
5. A data structure organizes data and operations
A data structure organizes data together with access, insertion, deletion and other operations. Identical values might occupy numbered slots, or a structure accessible primarily from the top. Different operations become easy or expensive.
An array uses indexed slots; the usual model allows direct access to a specified slot. A stack primarily operates at one end: the last item placed is removed first. Later lessons define and implement both carefully. For now separate “which values exist?” from “how can we access them?”
The maximum algorithm needs an ordered traversal. Our analysis assumes reading the next number and comparing two numbers each have constant cost. If access itself is more expensive, account for it separately.
6. A first cost analysis: what is counted?
Input size n is the number of entries. The first initializes best; each of the remaining n−1 entries needs one comparison. For nonempty input this procedure therefore uses exactly n−1 comparisons.
Four entries require three; one requires zero. Updates to best differ from comparisons. Ascending input changes best every later step; descending input never changes it after initialization, yet still performs every comparison.
Under constant-cost assumptions, time grows linearly with data count; later notation such as Θ(n) expresses this precisely. It does not mean “n seconds” or identical speed on every device.
Without extra information, ignoring an entry is dangerous: the unseen number could exceed every examined number. If a guaranteed upper bound is one hundred and we encounter one hundred, early termination can be valid. Different problem assumptions can permit different methods.
7. Test-taking notes, with reasons
- Initialize from the allowed domain: zero fails for all-negative lists; the first entry is safe for nonempty input.
- Name the cost: comparisons, assignments and iterations are not interchangeable.
- Check n=1: return that entry with zero pairwise comparisons.
- Sorting is unnecessary: finding only the maximum does not require ordering every entry.
- One counterexample refutes a universal claim: a method examining only the first two entries fails on
2, 3, 100.
These notes and the following questions are original educational material, not claimed past exam questions.
8. Independent practice: solve before opening answers
- Trace best after every entry in
8, 3, 11, 6and count comparisons.
Answer and reasoning 1
8, 8, 11, 11; three comparisons. Initialization reads the first entry without comparing it to itself. Best changes only once after initialization.
- On
−5, −2, −9, what does zero initialization return, and why is it wrong?
Answer and reasoning 2
It keeps zero because no entry exceeds it. The correct maximum is minus two. Zero is not an input entry; the failure is an invalid initialization assumption.
- Original practice question: On five entries, which always holds? A) Best changes four times. B) Four entry-to-best comparisons occur. C) The last entry is the answer. D) Sorting must come first.
Answer and reasoning 3
B. Four comparisons occur regardless of entry order. Update count depends on values; the last entry need not be largest and sorting is unnecessary.
- For the single entry minus seven, state initialization, comparison count and output. What about empty input?
Answer and reasoning 4
Best is minus seven, comparisons zero, output minus seven. Empty input has no maximum under this contract and should report that condition, not a fabricated zero.
- A method checks only the first two numbers and reports the larger. Give a counterexample, then name an extra assumption allowing early termination.
Answer and reasoning 5
4, 5, 20 defeats it. A guaranteed upper bound permits stopping when that bound is reached, because no larger value is possible. The general maximum problem did not supply such a bound.
9. Reconstruct without looking, then continue
Explain problem versus algorithm versus data structure. Explain why the maximum-of-examined-prefix statement survives the next step. Then trace a fresh list with negatives and duplicates.
Continue when: exercises 1, 2 and 4 have reasons and you distinguish comparisons from updates. For tracing difficulty, use four physical cards and write best after each. For counting errors, separate initialization from comparison steps.
Later trace −4, −4, −10, −1 and give a two-sentence correctness explanation. This suggests review, not a study record or automatic schedule. Next in this chapter are cost models and growth; not all DS-01 is available yet. Data structures contents · Start from foundations.
References and authorship
Text, examples, questions and diagram are original teaching material, not reproduced book text or official questions. Suggested further reading: Cormen and colleagues, Introduction to Algorithms, introductory algorithm/analysis material; Pat Morin, Open Data Structures, foundational concepts. These recommendations do not claim online review or verified 1406 exam allocation. Diagram provenance.
Next lesson: Cost analysis from scratch: counting work and time growth