solution1 - CMPT 307 — Data Structures and Algorithms...

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CMPT 307 — Data Structures and Algorithms Outline Solutions to Exercises on Heaps and Stable Matchings 1. Describe a Θ( n log n ) time algorithm that, given a set S of n integers and another integer x , determines whether or not there exist two elements in S whose sum is exactly x . The following algorithm solves the problem: 1. Sort elements in S . 2. Form the set S prime = { z : z = x- y for some y ∈ S } . 3. Sort the elements in S prime . 4. If any value in S appears more than once, remove all but one instance. Do the same for S prime . 5. Merge the two sorted sets S and S prime . 6. There exist two elements in S whose sum is exactly x if and only if the same value appears in consecutive positions in the merged output and this value is not x/ 2 . Observe that if any value appears twice in the merged output, it must appear in consecutive positions. Thus, we can constrain our search for repeated values to consecutive positions. Suppose that some value w appears twice. Then w appeared once in S and once in S prime . Because w appeared in S prime , there exists some y ∈ S such that w = x- y , or x = w + y . If w = x/ 2 , then y = x/ 2 , and since S is a set this value appears only once in S . Otherwise, since w ∈ S , the elements w and y are distinct elements in S that sum to x . Conversely, suppose that there are values w,y ∈ S such that w + y = x . Then, since x- y = w , the value w appears in S prime . Thus, w is in both S and S prime , and so it will appear twice in the merged output. Steps 1 and 3 require O ( n log n ) time. Steps 2,4,5, and 6 require O ( n ) time. Thus the overall running time is O ( n log n ) . 2. Suppose that in the MergeSort algorithm the input sequence split into k subsequences ( k > 2 , but fixed). Determine the running time of such algorithm. Does it have any advantages comparing to the standard MergeSort? (You may wish to look into Chapter 4 of CLR.) Let us assume that on an input sequence of length n the algorithms does O ( n ) work, that is, spends Cn time on each call, and that it splits the input sequence into...
View Full Document

This note was uploaded on 11/19/2009 for the course CS CMPT 307 taught by Professor A.bulatov during the Fall '09 term at Simon Fraser.

Page1 / 4

solution1 - CMPT 307 — Data Structures and Algorithms...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online