This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: CSE310 HW04, Thursday, 03/11/2010, Due: Thursday, 03/25/2010 Please note that you have to typeset your assignment using either L A T E X or Microsoft Word. Hand-written assignment will not be graded. You need to submit a hardcopy before the lecture on the due date. You also need to submit an electronic version at the digital drop box. For the electronic version, you should name your file using the format HW04-LastName-FirstName. 1. (10 pt) Give the exact number of element-wise comparisons needed to find both the smallest and the largest elements in an array of n un-sorted elements. Give the exact number of element-wise comparisons needed to find both the smallest and the second smallest elements in an array of n un-sorted elements. Note that you are not supposed to use asymptotic notations to answer these questions. Solution: Let f ( n ) denote the number of comparisons needed to find both the smallest and the largest elements in an array of n elements. First consider the case where n is even. Let n = 2 k . For k = 1, we only need one comparison. Therefore f (2) = 1. Suppose we have computed the largest and the smallest elements among the first 2( k − 1) elements, using f (2 k − 2) comparisons. For the next two elements, we need 3 comparisons. Therefore f (2 k ) = f (2 k − 2) + 3. This leads to f ( 2k ) = 3k − 2 for k = 1 , 2 , . . . . Now consider the case where n is odd. Let n = 2 k + 1. For k = 0, no comparison is needed, i.e., f (1) = 0. For k = 1 , 2 , . . . , f (2 k + 1) = f (2 k ) + 2, because the last element needs to be compared with both the candidate for largest and the candidate for smallest. Therefore f ( 2k + 1 ) = 3k for k = 0 , 1 , 2 , . . . . Combining both cases, we have f ( n ) = ⌈ 3 2 n ⌉ − 2 ....
View Full Document