{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# hw1soll - Analysis of Algorithms Homework I(Solutions K...

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

Analysis of Algorithms - Homework I (Solutions) K. Subramani LCSEE, West Virginia University, Morgantown, WV { [email protected] } 1 Problems 1. Write a recursive algorithm to check whether an integer x , exists in an array A of n integers. Solution: Algorithm 1.1 searches for an integer x in array A [ n ] . It returns true , if x A and false otherwise. Function A RRAY -S EARCH ( A , x, n ) 1: if ( n = 1 ) then 2: if ( A [1] = x ) then 3: return ( true) 4: else 5: return ( false) 6: end if 7: else 8: if ( A [ n ] = x ) then 9: return ( true) 10: else 11: A RRAY -S EARCH ( A , x, n - 1) 12: end if 13: end if Algorithm 1.1: Array Search 2. Argue the correctness of your algorithm using induction. Solution: Let P ( n ) denote the proposition that Algorithm 1.1 correctly searches for x in an array of size n . Base case ( n = 1) : Observe that when n = 1 , only lines 1 through 5 of Algorithm 1.1 are executed. If x A , then the conditional in the if statement of line 2 is satisfied and hence true is returned. Likewise, if x A , the conditional is falsified and hence line 5 of Algorithm 1.1 is executed, i.e., false is returned by Algorithm 1.1. We have thus

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.

{[ snackBarMessage ]}