Slideshow

Monday 25 February 2013


248 Sketch an algorithm to find the minimum and the maximum elements from a
sequence of n elements. Your algorithm should not take more than (3n/2)-2
number of comparisons where n is a power of 2. 

Ans:
Rather than processing each element of the input by comparing it against the correct
minimum and maximum, at the cost of 2 comparisons per element, we process
elements in pairs. We compare pairs of elements from the input first with each other,
and then we compare the smaller to the current minimum and the larger to the
current maximum, at the cost of 3 comparisons for every 3 elements.
If n is off, we set both the minimum and maximum to the value of first element and
the process the rest of the elements in pairs.
If n is even, we perform 1 comparison on the first 2 elements to determine the initial
values of minimum and maximum, and the process the rest of the elements in
pairs.So if n is odd, we perform 3[n/2] comparisons.
If n is even, we perform one initial comparison followed by 3(n-2)/2 comparisons for
a total of 3n/2-2. Thus in either, number of comparisons are almost 3[n/2]
Q.

No comments:

Post a Comment