CS2223
HW#3

Due: Monday, November 17

1. (10 points) Consider the computational model in which the benchmark operation is a pairwise comparison (the algorithm can select any two objects from the set and ask which is larger). In class we showed that according to this model, the problem of finding the largest element of a set of n distinct elements must use at least n-1 comparisons. Consider the problem of finding the second largest element of a set of n elements.
(a) Describe an algorithm to identify the second largest element such that the best case performance of the algorithm uses n-1 pairwise comparisons.
(b) Show that according to this computational model, any algorithm to identify the second largest element of the set must also be able to identify the largest. That is, after performing its sequence of comparisons, enough information must have been gleaned to permit the identification of the largest and the second largest elements, and to know which is larger.

2. (14 points) Consider the data structure search tree (described on pp. 157®159 of our text) to implement the abstract data type set. 
(a) What is the smallest possible height of a search tree of n nodes?
(b) What is the largest height possible for a search tree of n nodes? Describe an input permutation which yields this worst-case height.
(c) In order to estimate the average height (assuming all input permutations occur with equal probability) of a search tree of n nodes, program and test routines to make a search tree, to insert a node into a search tree, and to compute the height of a search tree. 
	• Grow random search trees of heights 23, 24, 25,… nodes.
	• Compute the heights of your trees.
	• See if you can find a constant c such that the heights are approximately clgn. 

CS2223
HW#3 Solutions

1. (a) Guess (& verify in n-1 comparisons) that the list is sorted. If it isn’t, sort it. Return the next to the last element.
	sorted=1;
	for (i=0;i<n-1;i++)
		if (A[i]>A[i+1]) sorted=0;    /* executed n-1 times*/
	if (!sorted) InsertionSort(A);
	return A[n-2];
(b) The algorithm must be able to identify the n-2 “losers” (elements which are not among the two largest), and hence identify the two “winners”. If the n-2 losers weren’t identified (didn’t each lose a comparison), then one of them could be changed to ∞ and the algorithm would still identify it as a loser (all the comparisons returned the same result). If, having identified the two winners, they were never compared to each other, then the algorithm couldn’t identify the smaller of the two (if the input reversed them, then the algorithm would persist in identifying the now incorrect second largest).

2. (a) 
(b) If the input is sorted, in increasing or decreasing order, the height is n-1. Note that these are not the only worst-case instances.