CS2022/MA2201
HW#4

Due: Thursday, September 18

1. (5 points) 	• How many “>“ comparisons does the following program segment do in the worst-case to find the two largest elements in an array A containing n elements? We assume A has at least two elements. Do not count the comparisons to run the “for” loop, only the comparisons which compare elements of A. Do not use O-notation; give the exact number of comparisons.
		• Describe an input which makes the algorithm take this much time.

	if (A[0]>A[1]) {big=A[0]; second=A[1];}
	else { big=A[1]; second=A[0];}
	for (k=2;k<n;k++)
		if (A[k]>second)
			{if (A[k]>big) {second=big; big=A[k];}}
		else second=A[k];

2. (3 points) Do Exercise 2.2.8 from our text.

3. (6 points) Do Exercise 2.2.12 from our text. Do not use O-notation; give the exact number of comparisons.

4. (5 points) Do Exercise 3.1.2 from our text.

5. (5 points) Do Exercise 3.1.10 from our text.

CS2022/MA2201
HW#4 Solutions

1. For a worst-case instance A[k]≤A[k+1], 0≤k<n-1, the algorithm requires 2n-3 comparisons.

2. b) n multiplications and n additions

3. a) n-1
b) 1
c) 

4. a) simplification
b) disjunctive syllogism
c) modus ponens
d) addition
e) hypothetical syllogism

5. Theorem: The sum of any two rational numbers is a rational number.
Proof: Let x and y be any two rational numbers. Then there must exist integers p, q, r and s such that x=p/q and y=r/s. Then . Since p, q, r and s are integers, then so are sp+qr and qs, and hence x+y can be expressed as the ratio of integers and it must be a rational number.