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: Problem 1 The following algorithm solves the problem : 1. Sort the elements in S . 2. Form the set S = { z  z = x y , y S } . 3. Sort the elements in S . 4. Merge the two sorted lists from steps 1 and 3. 5. There exist two elements in S whose sum is exactly x if and only if some element in the merged list from step 4 appears twice. Steps 1 and 3 require O ( n lg n ) steps. Steps 2, 4 and 5 require O ( n ) steps. Thus the overall running time is O ( n lg n ). Obvious improvements of the running time can be achieved by using counting sort or radix sort. Problem 2 a The asymptotic running time of Horners rule is ( n ). Each iteration of the loop performs a constant amount of work (one multiplication, one addition, and one subtraction) and iterates n times. b The following code evaluates a polynomial at x by computing each term of the polynomial from scratch. 1 y = 0 2 i = n 3 while i 4 z = 1 5 j = i 6 while j > 7 z = z x 8 j = j 1 9 y = y + a i z 10 i = i 1 For this algorithm, computing the term a k x k requires k + 1 multiplications, k + 1 subtractions, and one addition. Thus evaluating the whole polynomial takes time n k =0 2 k +3 = 2( n ( n +1) / 2)+ 3( n + 1) = ( n 2 ) A smarter algorithm for computing x k by successive squaring requires only (lg k ) multiplica tions per term. Using this method takes ( n lg n ) time to evaluate the polynomial....
View Full
Document
 Fall '11
 KENDER
 Algorithms, Sort

Click to edit the document details