Quiz #1 – comments

Here is one correct algorithm that locates the position of the largest even integer in a set of n integers:

procedure largest even location (a_1, a_2, . . . , a_n : integers)
k := 0
largest := -\infty
for i := 1 to n
if (a_i is even and a_i \geq largest) then
  k := i
  largest := a_i
return k {the desired location (or 0 if there are no even integers)}

There are certainly many correct ways to achieve this result, but this one is nicely compact. One of the trickiest parts for many of you was that initial value for largest. Some of you started with the value a_1 there, but would run into problems with input lists where the first element is a large odd number. Some of you started with the value 0 there, but would run into problems with input lists where there are even integers, but they’re all negative. Starting with -\infty clears this hurdle.

Most people’s pseudocode was fairly readable, but I want to emphasize that starting with the name of the procedure and a description of the inputs is critical for communicating what you’re doing. Some people’s answers were more code than pseudocode, which tended to make them less readable. Pseudocode isn’t a language, so there aren’t precise rules, but a nice description is given in the Appendix of your text. Roughly, you should be able to give pseudocode to a human who doesn’t understand code, but who is very good at following directions, and have him or her be able to understand it. When in doubt, show it to someone.

When you’re writing these short, simple algorithms, you should always check your work using a short example input. Some of you would have caught your initial error immediately and others would have noticed that their algorithm wasn’t returning any answer. Again, when in doubt, show your work to someone.

This entry was posted in Quizzes. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *