Imagine that you keep a list of books you have read. You want to find one title. You could start at the top and check each entry until you find it. That is already an algorithm: it gives you a sequence of steps and a point at which to stop. It is simple, but simple does not mean careless. We still need to say what happens if the title is not there and whether two books can have the same title.
Background for this page. An input is the information a method receives; an output is its answer. You only need to follow a short sequence of instructions. Related explanations: Insertion sort: a worked example and its cost · Big O, Big Omega, and Big Theta.
1.1 A method needs a clear job
An algorithm is a finite, precise method for a defined task. It takes an input, follows steps, and produces an output. For our book search, the input is a list of titles and a title to find. The output might be the position of the first match or the message “not found.” We must choose which before writing code.
Here is one possible method. The comments explain each step. Use Hide explanations above the block to see the method alone; Copy takes the version you can see.
# Visit each title in order.
for each position in the list, from first to last:
# Stop when this title matches the target.
if the title at that position matches the target:
# Report the position where it was found.
return that position
# If the loop finishes, no title matched.
return not found
The last line matters. Without it, the instructions say nothing about a missing title. The word matches also hides a decision. Should The Moon match the moon? Should spaces at the ends count? A program will make some choice even if its writer never thinks about it. A useful problem statement makes that choice visible.
The numbered checks show why the search returns 2. It stops as soon as it finds a match. If it reached the end without one, it would return “not found.”
Try it on paper. Search ["River", "Moon", "Garden"] for "Garden", then for "Cloud". The first search returns position 2 if we number positions from 0. The second checks every title and returns “not found.”
1.2 Correct answers come before fast answers
Suppose someone suggests a faster method: look at the middle title, then search only half the list. That sounds attractive. It works as a basis for binary search only when the list is sorted by the same rule used for comparisons. Our list is not sorted, so throwing away half could discard the answer.
This is a general habit worth learning early: before asking how fast a method is, ask what must be true for it to work. We call these conditions its assumptions or preconditions. We also need to know what the output promises. If the list contains "Moon" twice, the method above returns the first match it reaches. It does not return every match.
We can gather evidence by testing an ordinary case, an empty list, a missing title, and a repeated title. A successful test is helpful, but a handful of tests cannot cover every possible input. Later we will also make short arguments about why an algorithm is correct. For the search above, the argument is: every earlier entry has already been checked before we reach a position. If we find a match, we return a matching position. If we finish the list, no entry matched under our chosen rule.
1.3 Time and memory are resources
If the title is first, the search checks one entry. If it is last or missing, it checks every entry. For a list of 10 items, that may be fine. For millions of items searched repeatedly, we may want a different arrangement of data. This is why algorithms and data structures belong together: the way data is stored changes what methods are available and what they cost.
We will often count operations instead of timing a computer. Elapsed time depends on hardware, language, and other work the computer is doing. Counting lets us ask how the work grows as the input grows. Here, the number of comparisons is at most the number of titles, which we can call n. The method also needs only a small amount of extra working space beyond the input list.
Speed is not the only goal. A method should answer the right question, handle unusual inputs, and be understandable enough to maintain. A reliable slow answer can be improved. A quick wrong answer is still wrong.
1.4 Algorithms turn choices into repeatable steps
Algorithms do not live only in textbooks. A navigation app chooses a route. A search service decides which pages match your words. A program checks whether a password meets a rule. In each case, the real work begins by deciding what the input and output mean. “Best route” might mean shortest distance, least travel time, or lowest cost. Those are different problems and may produce different answers.
This course will study ways to solve such problems, and also the limits of those ways. Some methods guarantee an exact answer. Some use randomness. Some give a useful approximation when an exact answer would take too long. The first step is always to state the job clearly.
Why the input contract matters
Find the largest number in [-8, -3, -11]. Start with the first item, -8. Comparing -3 changes the saved maximum to -3; comparing -11 leaves it there. Starting at zero would return a value absent from the input. After each comparison, the saved value is the maximum of the examined prefix. When the prefix becomes the whole list, that statement proves the answer correct. An empty list needs a separate policy because it has no maximum.
Practice. A reading log contains minutes for each day. Design a method that returns the total. State what it does with an empty log and a negative number. Then trace your method on [20, 0, 15].
One reasonable answer. Start the total at zero. For each entry, reject it if it is negative; otherwise add it. Return the total after the final entry. An empty log returns zero. The trace gives 20, then 20, then 35. Other rules for bad entries are possible, but they must be stated and followed consistently.
Next we will write and compare two ways to sort a small collection. Sorting will give us a concrete setting for discussing correctness and cost.
Try another case. How would you return the first position of a maximum when values tie?
Reasoning. Save the position with the value, and update only for a strictly larger value. Updating on equality selects the last maximum.