Here is the algorithm example for the week 8 discussion

advertisement
Here is the algorithm example for the week 8 discussion. Since there were no classes on the
13th, it will be discussed the week of March 27 in Cindy’s discussion.
Example 1: Design and analyze a pseudocode algorithm that finds the sum of the even
numbers in a list of length n. Analyze the number of assignments made in both the best and
worst cases. You may assume there are Boolean functions odd and even that return true if a
number has the respective property. The first element on the list is a 1. Be sure to check for
the extremal case—no even numbers or a single even number.
integer sum, i, j
sum  1
i1
while (i  n and ai is odd)
ii+1
if i  n then
sum  ai
for j  i+1 to n
if even(aj) then sum  sum + aj
return (sum)
else
return(“There are no even numbers”)
(1)
(2)
(3)
(4)
(5)
(6)
Steps (1) and (2) each have one assignment
Step (3)—if a1 is even and there are no assignments
if all integers are odd and the assignment is made n times
Step (5)—if there is at least one even number one assignment is made
Step (6)—If the list has only even numbers, the assignment is made n – 1 times.
Best case: the first number and no others are even
total number of assignments: 3 (steps (1), (2) and (5))
Worst case: all numbers are even. Assignments are made in steps
(1), (2), (5) and (6) for a total of n + 2 [1 + 1 + 1 + n-1]
Example 2: (to be worked out in the discussion). Write and analyze a pseudocode algorithm
that finds the product of the largest and smallest even integers in the list a 1, a2, …, an. The
algorithm should return -1 (or some other negative value) if there are no even numbers. If
there is just one even number a special value should be returned so that the user can
recognize that fact. Determine how many comparisons of list items the algorithm requires in
both the best and worst cases. Common errors to watch out for: using more than one pass to
find both the smallest and largest even numbers, and initializing the big and small values to 0
or some other constant that may never get reset. Remember that the product could be 0 since
there are no restrictions on the numbers in the list—they could be positive, negative or zero.
Download