(a) Use pseudocode to describe an algorithm for finding the largest and second largest elements in a list of integers.
procedure largest_and_2nd_largest
if
then
else
for to
if
then
else if
then
return
{ is the largest element in the list; is the second-largest element in the list}
(b) Show each step of your algorithm from (a) when it is applied to the set {1, 6, 4, 2, 5}
Step 1: compare and :
Is ? No, so the initial value of is and the initial value of is .
Step 2: :
Is ? No.
Is ? Yes, so we redefine as .
Step 3: :
Is ? No.
Is ? No.
Step 4: :
Is ? No.
Is ? Yes, so we redefine as .
The algorithm then returns .
(c) Determine the number of comparisons used by your algorithm in (a). Explain your answer. (You may ignore comparisons needed to determine whether the end of a loop has been reached.)
There is one comparison before the loop: versus .
There are values of inside the loop.
Each value of includes at most two comparisons: versus and versus .
Therefore there are comparisons overall. (Note that this ignores comparisons needed to determine whether the end of a loop has been reached.)
Part (a) was a challenge for many of you. Some of you had algorithms that returned the largest element in the list twice, some of you had algorithms that returned the largest and smallest elements in the list, some of you had algorithms that worked only if all elements were positive. The algorithm above isn’t the only one that works; many of you had correct answers that looked completely different.
As in #2, you’ll want to make to use “return” only once at the end when you’re ready to spit out the outputs.
Part (b) was another tricky question where many of you didn’t appear to look at your answer for (a). Again, the point of (b) was so you could check your answer for (a). Some of you included unexpected notation in your answer for (b) and didn’t state clearly what each of your steps were, so it was hard for me to tell whether what you were doing for (b) actually matched what your algorithm in (a) told you to do or not.
Again, for part (c), many of you looked at your answer for (b) instead of (a) and/or included a big-O estimate for the complexity of your algorithm. Don’t forget to read the question carefully and answer what is asked for.