Docsity

Recursion in Discrete Structures: Recursive Definitions and Algorithms, Study notes of Discrete Structures and Graph Theory

Partial preview of the text

Download Recursion in Discrete Structures: Recursive Definitions and Algorithms and more Study notes Discrete Structures and Graph Theory in PDF only on Docsity!

10/11/

CSci 243

Discrete Structures

Lecture 16Recursion II

10/11/

Outline^ • Recap: Recursive Definitions• Recursive Algorithms• Lots of Examples and Problems• Introduction to Program Verification

10/11/

Recursive Algorithms^ •

Recursive algorithm: an algorithm which solves aproblem by dividing the problem into similarsub-problems, and then solving them.

Divide and conquer: split the problem into sub-problems, and repeat until problems are easy tosolve. (Often, but not necessarily recursive.)

10/11/

Example: Sequential Search^ list::iterator

linear_search(list

a_list,

int

search_int,

list::iterator

NOT_FOUND)

{

if

(a_list.size()

==

return

NOT_FOUND;

list::iterator

beginning

=

a_list.begin();

list

remainder

=

a_list;

remainder.pop_front();if

(*beginning

==

search_int)

return

beginning;

else

return

linear_search(remainder,search_int,

NOT_FOUND);

}

10/11/

QC: Powers Algorithm^ • Write a function pow(b,e) (b,e integer, e

which computes b

e^

using multiplication (and

recursion!)

10/11/

Example: Fibonacci Numbers^ int fib(int n){

// First easy caseif n == 1

return 0 // Second easy caseelse if n == 2

return 1 // Hard caseelse

return fib(n-1) + fib(n-2)

}

10/11/

QC: A Different Powers Algorithm^ • Write a function big_power(b,e) which computes• Example: big_power(3,3)• Note: Use pow(b,e) to compute b

e

(^

(^

)^

1 ... 2

1

   

   

  

^  

−

−^

e

e e b

(^

(^

)^

(^

)^

729

27

3

1 2

1 2 3

=

=

10/11/

Next up… Program Verification

10/11/

Partial Correctness^ • Program segment S• Initial condition p on inputs• Final condition q on outputs• p{S}q (Hoare triple): Segment S is

partially

correct p is true, S terminates, and q is true

  • Recall: Halting problem

10/11/

Build Up Proof^ • Segments S

1

and S

2

  • If p{S

}q and q{S 1

}r, then p{S 2

;S 1

}r 2

(Just a composition rule!)

  • Example:

y = 2;

Å

S

1

z = x+y;

Å

S

2

p: x=1, q: z=

10/11/

Example^ • Prove the following:

-^

p: true

-^

q: y

≥

x

-^

S: if (x>y) then y=x

10/11/

Quick Question^ • Code: if

condition then

S

1

else

S

2

  • What is the inference rule?• (p

condition){

S

}q 1

(p

condition){

S

}q 2

à

p{if

condition then

S

1

else

S

}q 2