Question 2 15 points Consider functions max and min so that
Question 2 (15 points): Consider functions max and min so that max(a1,a2,...,an) and min(a1,a2,...,an) are the maximum and minimum of the n numbers a1, a2, . . . , an, respectively.
a) Give recursive definitions of the functions max and min.
b) Give recursive algorithms for finding max and min.
c) Prove that the recursive algorithms that you found in part b are correct.
Solution
max(a1)=a1 min(a1)=a1
max(a1, a2) = a1 if a1 a2, min(a1, a2) = a1 if a1 a2,
a2 if a2 a1 a2if a2 a1,
max(a1, . . . , an) = max(max(a1, . . . , an1), an), min(a1, . . . , an) = min(min(a1, . . . , an1), an).
the original definitions of max and min for n 2, hence our base case is already guaranteed to be true. Now suppose that the extended definitions of max and min compute the maximum or minimum element for a list of length (n 1); we will show that this entails that they compute the correct value for a list of length n.
Let m = max(a1, . . . , an) = max(max(a1, . . . , an1), an) = max(a1, . . . , an1). In this case, m an by the outer max, and by inductive assumption, m ai for all 1 i < n by the inner max and moreover m is one of the ai . These are the two defining properties of max, and hence our definition computes it correctly.
Suppose m = an instead. In this case, an max(a1, . . . , an1) — but, as max(a1, . . . , an1) ai for 1 i < n, transitivity shows an ai for all i in this range. Hence, an is the maximum element, and our definition computes max correctly.
If the inequalities reversed ,the proof of correctness for minimum proceeds the same.
