Mid Term 1 Solution

Only available on StudyMode
  • Topic: Sorting algorithm, Heap, Heapsort
  • Pages : 2 (534 words )
  • Download(s) : 59
  • Published : November 26, 2012
Open Document
Text Preview
COT5405 Analysis of Algorithms Midterm 1 Solution
Summer 2012 June 11 In all cases explain clearly and as succinctly as possible. Problem 1 10 Pts

Answer: n T (n) = 2T ( n ) + log n 2 2 n = 4T ( n ) + logn n + log n 4 2 2 2 n = 4T ( n ) + log nn−1 + log n 4 2 2 = ... ∑log2 n 1 = nT (1) + n i=1 i ∑n Since i=1 1 → ln n, T (n) ∈ Θ(n log log n) i

Problem 2

20 Pts

Answer: The general idea is to use the technique similar to quick sort, by doing partition on both lids and cups. First we pick a cup randomly, and use it to partition the lids into two subsets: those lids smaller than the size of that cup, and those larger than the size of the cup. We can also find the correspondent lid for that chosen cup. Second we use that lid to partition the cups and divide them into two sets. We keep on repeating this procedure on each subset of cups/lids until all the cups/lids are paired. The overall time complexity is O(n log n) (Worst case: O(n2 )).

Problem 3

20 Pts

Answer: In this problem we are more interested in finding the median instead of the minimum/maximum element. The ⌊ n ⌋th element in a min/max heap is not the median. 2 In this case, we should develop a new type of heap to adapt this problem.

Problem 3

2

The solution is to use two heaps: a min heap and a max heap. Suppose the total number of elements is n, we set the restriction that the max heap should contain ⌊ n ⌋ 2 elements. Correspondingly, the min heap contains n − ⌊ n ⌋ elements. 2 When we insert an element, we always insert it into the max heap. If the number of elements in the max heap exceeds ⌊ n ⌋, we remove the maximum element in the 2 max heap (the root), and insert it into the minimum heap. During this procedure, we need to do heapify to maintain the heap structure for both heaps. Under this setting, it is easy to see that all the elements in the max heap are less than those in the min heap, and the two elements at the root of both heaps represent the ⌊ n ⌋th 2 and (⌊ n ⌋ +...
tracking img