(a) Use pseudocode to describe an algorithm that takes a list of
integers
and finds the number of integers greater than 5 in the list.
procedure greater_than_5![(a_1, a_2, \dots, a_n\: integers) (a_1, a_2, \dots, a_n\: integers)](https://s0.wp.com/latex.php?latex=%28a_1%2C+a_2%2C+%5Cdots%2C+a_n%5C%3A+integers%29&bg=ffffff&fg=000000&s=0)
count:=0
for
to ![n n](https://s0.wp.com/latex.php?latex=n&bg=ffffff&fg=000000&s=0)
if ![a_i > 5 a_i > 5](https://s0.wp.com/latex.php?latex=a_i+%3E+5&bg=ffffff&fg=000000&s=0)
then count := count + 1
return count
(b) Show each step of your algorithm from (a) when it is applied to the set {1, 6, 4, 2, 5}.
Step 1, i=1:
Is
? No, so count stays at 0.
Step 2, i=2:
Is
? Yes, so count is redefined as 0+1=1.
Step 3, i=3:
Is
? No, so count stays at 1.
Step 4, i=4:
Is
? No, so count stays at 1.
Step 5, i=5:
Is
? No, so count stays at 1.
Therefore algorithm returns count = 1.
(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.)
The algorithm in (a) has a loop which uses
values of
. Each value of
gives one comparison:
versus 5. Since there are no comparisons outside the loop, the algorithm uses
comparisons. (Notice that this ignores comparisons needed to determine whether the end of a loop has been reached.)