Analysis of Algorithm sol1

# Analysis of Algorithm sol1 - Problem 1 The following...

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
This is the end of the preview. Sign up to access the rest of the 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 Horner’s 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

{[ snackBarMessage ]}

### Page1 / 5

Analysis of Algorithm sol1 - Problem 1 The following...

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

View Full Document
Ask a homework question - tutors are online