# problems06-sol - MATH S-104 Lecture 6 In-class Problem...

This preview shows pages 1–3. 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: MATH S-104 Lecture 6 In-class Problem Solutions July 9, 2009 Problem 1 Prove that the recursive factorial algorithm is correct. Algorithm 4.0: A recursive algorithm for computing n ! procedure factorial ( n ∶ nonnegative integer) if n = then factorial ( n ) ∶ = 1 else factorial ( n ) ∶ = n ⋅ factorial ( n- 1 ) • Base case : n = 0. The algorithm returns 1, which is the correct result for n !. • Inductive step : Assume that the algorithm computes k ! correctly. Thus we know that factorial ( k ) = k !. The algorithm sets factorial ( k + 1 ) to be ( k + 1 ) * factorial ( k ) , which, because of the inductive hypothesis, ( k + 1 ) k !. Thus the result computed by the algorithm for factorial ( k + 1 ) = ( k + 1 ) ! as it should. Problem 2 * : Prove that if f 1 ( x ) is O ( g 1 ( x )) and f 2 ( x ) is O ( g 2 ( x )) , then f 1 f 2 ( x ) is O ( g 1 ( x ) g 2 ( x )) . We know that • f 1 ( x ) ≤ C 1 g 1 ( x ) for x > k 1 • f 2 ( x ) ≤ C 2 g 2 ( x ) for x > k 2 f 1 ( x ) f 2 ( x ) = f 1 ( x ) f 2 ( x ) ≤ C 1 g 1 ( x ) C 2 g 2 ( x ) ≤ C 1 C 2 ( g 1 g 2 )( x ) ≤ C ( g 1 g 2 )( x ) So C = C 1 C 2 and k = max ( k 1 ,k 2 ) are witnesses. 1 Problem 3 Write pseudocode for a function, merge , which takes two sorted lists of integers, and returns a sorted list of all of the elements from both lists. What is the worst-case complexity for your merge algorithm, in terms of comparisons performed? Algorithm 4.0: Merging two lists procedure merge ( L 1 ,L 2 ∶ sorted lists) L ∶ = {} while length ( L 1 ) > ∧ length ( L 2 ) > e 1 = L 1 [ ] e 2 = L 2 [ ] if e 1 < e 2 then L.append ( e 1 ) L 1 .remove ( e 1 ) if length ( L 1 ) = then L.appendAll ( L 2 ) else L.append ( e 2 ) L 2 .remove ( e 2 ) if length ( L 2 ) = then L.appendAll ( L 1 ) { L is the merged list with elements in increasing order...
View Full Document

## This note was uploaded on 05/12/2010 for the course APPLIED ST 2010 taught by Professor Various during the Spring '10 term at Universidad Nacional Agraria La Molina.

### Page1 / 5

problems06-sol - MATH S-104 Lecture 6 In-class Problem...

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

View Full Document
Ask a homework question - tutors are online