{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# solution2 - COMP/MATH 3804 Design and Analysis of...

This preview shows pages 1–2. Sign up to view the full content.

COMP/MATH 3804 – Design and Analysis of Algorithms I Assignment 2 Due June 3 at the beginning of class Write down your name and student number on every page. The questions must be answered in order and your assignment sheets must be stapled. Late assignments will not be accepted. Students are encouraged to collaborate on assignments, but at the level of discussion only. When writing down the solutions, students must do so in their own words. 1. Suppose we are given n integers a 1 , a 2 , . . . , a n and an integer i with 1 i n . We want to report the i smallest numbers ( i.e. , the smallest, second smallest, third smallest, . . . , i -th smallest numbers) in sorted order . (a) One possible strategy is to use S ELECT to compute the smallest, second smallest, third smallest, . . . , i -th smallest individually. How long does this take? Solution: S ELECT takes O ( n ) time. Since we run it i times, the total running time is O ( ni ) . (b) One possible strategy is to sort the list and return the first i elements. How long does this take? Solution: Sorting takes O ( n log n ) time using, e.g. , merge sort. It then takes O ( i ) time to report the first i elements, for a total of O ( n log n + i ) = O ( n log n ) . (c) One possible strategy is to put all the elements into a heap and call E XTRACT -M IN i times. How long does this take? Solution: Building a heap on n elements takes O ( n ) time. Each E XTRACT -M IN takes O (log n ) time, and we perform i of them. The total running time is thus O ( n + i log n ) . (d) Describe and analyze an algorithm to perform this operation in O ( n + i log i ) time. Solution: We first call S ELECT to determine the i -th smallest element. We then call P ARTITION (the same one that is used as a subroutine of S ELECT ) in order to partition the input around the i -th smallest element. At this point, we have the smallest, second smallest, third smallest, . . . , i -th smallest numbers, but they may not be in sorted order. To sort these i numbers takes O ( i log i ) time using, e.g. , merge sort. The total time is therefore O ( n + i log i ) .

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 3

solution2 - COMP/MATH 3804 Design and Analysis of...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online