hw1soll - Analysis of Algorithms - Homework I (Solutions)...

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

View Full Document Right Arrow Icon
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 ARRAY-SEARCH ( 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: ARRAY-SEARCH ( A , x, n - 1) 12: end if 13: end if Algorithm 1.1: Array Search 2 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 6∈ 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
Background image of page 1

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

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

This note was uploaded on 05/11/2010 for the course COMPUTER S 301 taught by Professor . during the Spring '10 term at Kadir Has Üniversitesi.

Page1 / 3

hw1soll - Analysis of Algorithms - Homework I (Solutions)...

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