0% found this document useful (0 votes)
3 views

19-recursion-3

Uploaded by

elkoush390
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

19-recursion-3

Uploaded by

elkoush390
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Discrete Structures

Ind.&Rec.: Recursion
(Ch 5.3/5.4)*

CMPS 211 – American University of Beirut

* Extracted from Discrete Mathematics and It’s Applications book


slides
1
Recursive Definitions (Ch.
5.3)

2
Motivation
Consider the following sequence:
S = {1, 5, 9, 13, etc…}

Can we find a closed form for the i th element in the


sequences?

Si = 1 + 4i

Now consider the following sequence:


S = {1, 5, 29, 845, etc…}

Can we find a closed form for the i th element in the


sequences?

Well, we might able to, but it is easier to calculate the


value of Si based on the value of Si-1 as follows:

Si = Si-12 +4 & S0 = 1
3
Recursively Defined Functions
A recursive or inductive definition of a
function consists of two steps

BASIS STEP: Specify the value of the function at


zero (first element in the domain)

RECURSIVE STEP: Give a rule for finding its


value at an integer from its values at smaller

integers (i.e., a recurrence relation)

A function f(n) is the same as a sequence a0,


a1, …, an, where f(i) = ai

4
Recursively Defined Functions
Example: Suppose f is defined by:
f(0) = 3,

f(n + 1) = 2f(n) + 3
Find f(1), f(2), f(3), f(4)

Solution:
f(1) 2f(0) + 3 = 2∙3 + 3 = 9

=
f(2) = 2f(1)+ 3 = 2∙9 + 3 = 21

f(3) = 2f(2) + 3 = 2∙21 + 3 = 45


f(4) = 2f(3) + 3 = 2∙45 + 3 = 93



 Example: Give a recursive definition of the factorial function n!

Solution:
f(0) = 1

f(n) = n ∙ f(n-1)

5
Recursively Defined Functions
 Example: Give a recursive definition of:

 Solution:
 The first part of the definition is

 The second part is

Recall Induction on sequences!


6
Rabbits Riddle
Example: A young pair of rabbits (one of each
gender) is placed on an island. A pair of

rabbits does not breed until they are 2


months old. After they are 2 months old, each
pair of rabbits produces another pair each
month.

What is the number of pairs of rabbits on the


island after n months, assuming that rabbits

never die?

7
Modeling the Rabbits Population Growth

8
Rabbits Solution
Solution: Let fn be the the number of pairs of rabbits after n
months

 There are f = 1 pairs of rabbits on the island at the end of


1
the first month
 We also have f = 1 because the pair does not breed during
2
the first month
 To find the number of pairs on the island after n months, add
the number on the island after the previous month, fn-1, and
the number of newborn pairs, which equals fn-2, because each
newborn pair comes from a pair at least two months old
 Consequently the sequence { f } satisfies the recurrence
n
relation fn = fn-1 + fn-2 for n ≥ 3 with the initial conditions
f1 = 1 and f2 = 1
The number of pairs of rabbits on the island after n months is
given by the nth Fibonacci number

9
Leonardo of
Pisa Fibonacci
(1170- 1250)
Fibonacci Numbers
Example : The Fibonacci numbers are defined
as follows:

f0 = 0
f1 = 1
fn = fn−1 + fn−2

Find f2, f3 , f4 , f5
f2 = f1 + f0 = 1 + 0 = 1
f3 = f2 + f1 = 1 + 1 = 2

f4 = f3 + f2 = 2 + 1 = 3

f5 = f4 + f3 = 3 + 2 = 5


10
Recursive Algorithms (Ch.
5.4)

11
Recursive Algorithms
An algorithm is called recursive if it solves a
problem by reducing it to an instance of the

same problem with smaller input

For the algorithm to terminate, the instance of


the problem must eventually be reduced to

some base case for which the solution is


known

As we will see, recursive algorithms tend to be


much more elegant than iterative algorithms

12
Recursive Factorial Algorithm
Give a recursive algorithm for computing n!,
where n is a nonnegative integer

Solution: Use the recursive definition of the


factorial function

Basis step: 0! = 1
Recursive step: n! = n.(n-1)!

procedure factorial(n: nonnegative integer)


if n = 0 then
return 1
else
return n∙factorial(n − 1)
{output is n!}
13
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return n∙factorial(n − 1)
{output is n!} if n = 0 then
return 1
factorial(3) else
if n = 0 then return 1 return n∙factorial(n − 1){output
else return n∙factorial(n − 1) is n!}
{output is n!}

factorial(2)
if n = 0 then return 1
else return n∙factorial(n − 1)
{output is n!}

factorial(1)
if n = 0 then return 1
else return n∙factorial(n − 1)
{output is n!}

factorial(0)
if n = 0 then return 1
else return n∙factorial(n − 1)
{output is n!}

14
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return n∙factorial(n − 1)
{output is n!} if n = 0 then
return 1
factorial(3) else
if n = 0 then return 1 return n∙factorial(n − 1){output
else return n∙factorial(n − 1) is n!}
{output is n!}

factorial(2)
if n = 0 then return 1
else return n∙factorial(n − 1)
{output is n!}

factorial(1)
if n = 0 then return 1
else return n∙factorial(n − 1)

1
{output is n!}

15
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return n∙factorial(n − 1)
{output is n!} if n = 0 then
return 1
factorial(3) else
if n = 0 then return 1 return n∙factorial(n − 1){output
else return n∙factorial(n − 1) is n!}
{output is n!}

factorial(2)
if n = 0 then return 1
else return n∙factorial(n − 1)
{output is n!}

factorial(1)
if n = 0 then return 1
else return 1∙1{output is n!}

1
16
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return n∙factorial(n − 1)
{output is n!} if n = 0 then
return 1
factorial(3) else
if n = 0 then return 1 return n∙factorial(n − 1){output
else return n∙factorial(n − 1) is n!}
{output is n!}

factorial(2)
if n = 0 then return 1
else return n∙factorial(n − 1)

1
{output is n!}

17
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return n∙factorial(n − 1)
{output is n!} if n = 0 then
return 1
factorial(3) else
if n = 0 then return 1 return n∙factorial(n − 1){output
else return n∙factorial(n − 1) is n!}
{output is n!}

factorial(2)
if n = 0 then return 1
else return 2∙1{output is n!}

18
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return n∙factorial(n − 1)
{output is n!} if n = 0 then
return 1
factorial(3) else
if n = 0 then return 1 return n∙factorial(n − 1){output
else return n∙factorial(n − 1) is n!}

2
{output is n!}

19
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return n∙factorial(n − 1)
{output is n!} if n = 0 then
return 1
factorial(3) else
if n = 0 then return 1 return n∙factorial(n − 1){output
else return 3∙2{output is n!} is n!}

20
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return n∙factorial(n − 1)
if n = 0 then

6
{output is n!}
return 1
else
return n∙factorial(n − 1){output
is n!}

21
Recursive Factorial Algorithm
factorial(4) (n = 4) procedure factorial(n: nonnegative
if n = 0 then return 1 integer)
else return 4∙6{output is n!}
if n = 0 then

6
return 1
else
return n∙factorial(n − 1){output
is n!}

22
factorial(4)
Recursive Factorial Algorithm

=24
procedure factorial(n: nonnegative
integer)
if n = 0 then
return 1
else
return n∙factorial(n − 1){output
is n!}

23
Common Mistakes in Iterative Algs.
In iterative algorithms, its important to make
sure that loops terminate eventually, and not

to create infinite loops

 Example:

int result := 1
while (result > 0)

result := result + 1
Termination condition won’t be reached
since result is always positive

24
Common Mistakes in Recursive Algs.
Similarly, in recursive algorithms, we must be careful
not to create an infinite chain of function calls:

 Example:
procedure fact(int numb)
return numb * fact(numb-1)
No Termination condition! (infinite descent)
Or:
procedure fact(int numb)
if numb<=1 then
return 1;
else
return numb * fact(numb+1);
Infinite ascent since base case wont hold, & the
function will keep being called for larger and larger
values
25
Recursive Exponentiation Algorithm
Give a recursive algorithm for computing an,
where a is a nonzero real number and n is a

nonnegative integer
 Solution: Use the recursive definition of an
Basis Step: a0 = 1
Recursive step: an = a . an-1

procedure power (a: nonzero real number, n: nonnegative integer)


if n = 0 then
return 1
else
return a∙ power (a, n − 1)

{output is an}

26
Correctness of Recursive Algorithms
Induction is usually used to show that recursive algorithms
always produce the correct output

Example: Prove that the algorithm for computing the


powers of real numbers is correct

procedure power(a: nonzero real number, n: nonnegative


integer)
if n = 0 then return 1
else return a∙ power (a, n − 1)
{output is an}
Solution: Use mathematical induction on the exponent n
 BASIS STEP: a0 =1 for every nonzero real number a, and

power(a,0) = 1
 INDUCTIVE STEP: The inductive hypothesis is that power(a,k)
= ak, for all a ≠0
Assuming the inductive hypothesis, the algorithm correctly
computes ak+1, since power(a,k + 1) = a∙ power (a, k) = a∙ ak =

27
ak+1
Fibonacci Sequence
Construct a recursive algorithm to compute
the nth Fibonacci's number

Solution: Use the recursive definition of


Fibonacci

Basis Step: f(0) = 0 & f(1) = 1


Recursive step: f(n) = f(n-1) + f(n-2)

procedure Fibonacci(n: nonnegative integer)


if n = 0 then return 0
if n = 1 then return 1
else return Fibonacci(n-1) + Fibonacci(n-2)

{output is f(n)}

28
Recursive Binary Search Algorithm
 A divide-and-conquer algorithm
Works by first dividing the problem into smaller
instances of the same problem and then conquering the

problem using the solutions of the smaller problems


procedure binary search(A: a1,a2,…, an , i, j, x : integers, 1≤ i ≤ j ≤n)
m := ⌊(i + j)/2⌋ {initially i = 1 and j = n}
if i > j then {x is not in A}
return 0
else if x = am then {x is at position m in A}
return m
else if x < am then {we shall search for x in A[i … m-1]}
return binary search(A, i,m−1,x)
else if x > am then {we shall search for x in A[m+1 … j]}
return binary search(A, m+1,j,x)
{output is location of x in a1, a2,…,an if it appears, 0 otherwise}

29
Merge Sort
 Another divide-and-conquer algorithm
Iteratively split the input list into two sublists of
nearly equal size until each sublist has one

element
At each step a pair of sublists is successively
merged into a list with the elements in increasing

order
The process ends when all the sublists have been
merged

The succession of merged lists is represented by a


binary tree

Merge Sort
Example: Use merge sort to put the list
8,2,4,6,9,7,10, 1, 5, 3

into increasing order


 Solution:
Recursive Merge Sort
Construct a recursive merge sort algorithm
Solution: Begin with the list of n elements L

procedure mergesort(L = a1, a2,…,an )


if n > 1 then
m := ⌊n/2⌋
L1 := a1, a2,…,am
L2 := am+1, am+2,…,an
L := merge(mergesort(L1), mergesort(L2 ))
{L is now sorted into elements in increasing order}

continued
Recursive Merge Sort
Subroutine merge, which merges two sorted
lists

procedure merge(L1, L2 :sorted lists)


L := empty list
while L1 and L2 are both nonempty
remove smaller of first elements of L1 and L2 from its list;
put at the right end of L
if this removal makes one list empty
then remove all elements from the other list and append them to L
return L {L is the merged list with the elements in increasing order}
Merging Two Lists
Example: Merge the two lists 2,3,5,6 and 1,4
Solution:


Recursive Structures

35
Recursively Defined Structures
A recursive definition for structures is used to
define a structure that is composed of a

certain element and another instance of the


structure itself

Recursive definitions for structures consist of


two parts:

BASIS STEP: Specify the initial element of the


structure

RECURSIVE STEP: Give a rule for representing


the structure based on a smaller instance of the

same structure
36
Recursively Defined Sets
An infinite set S may be defined recursively,
by giving:

A small finite set of base elements of S


A rule for constructing new elements of S from

previously-established elements

 Implicitly, S has no other elements but these

Example: Let 3  S, and let x + y  S if x , y


S

What is S?

We have: 3  S and x,y (x,y  S  x + y


S)
37 So 3+3 = 6  S, 3+6 = 9  S, 6 + 6 = 12
The Set of All Strings
Given the set of alphabets Σ, build a recursive
definition of the set Σ*, where Σ* is the set of all

possible words over Σ

Basis step: λ  Σ* (λ :≡ “”, the empty string)


Recursive Step: if w  Σ*  x  Σ → wx  Σ*

Example: If Σ = {0,1}, the strings in Σ* are the set of


all bit strings λ,0,1, 00,01,10, 11, etc.

Example: If Σ = {a,b}, show that aab is in Σ*


Since λ ∊ Σ* and a ∊ Σ, a ∊ Σ*

Since a ∊ Σ* and a ∊ Σ, aa ∊ Σ*

Since aa ∊ Σ* and b ∊ Σ, aab ∊ Σ*



38
Set of Palindromes
A palindrome is a word that can be read from
left-to-right or from right-to-left

 mom, pop, eye, racecar, Eve

Given the set of alphabets Σ, build a recursive


definition of the set P, where P is the set of

all possible palindromic words over Σ


Basis step: λ  Σ* (λ :≡ “”, the empty string)
Recursive step: if w  Σ*  x  Σ → xwx  Σ* 

wxw  Σ*

39
Binary Tree
A binary tree is a data structure defined as
follows:

Basis Step: A tree with a single vertex (the root)


is a binary tree

Recursive step: if T1 and T2 are Binary Trees with


roots r1 and r2 respectively, then the following are

all Binary Trees

40
Example B-Trees

41
Recursive Procedures on Binary Trees
How can we recursively find the height of a
tree?

How can we sum up all values in the tree?


How can we find the max?

How can we count the number of nodes?


How an we count the number of leaves?


How can we ….

42
Binary Tree: Sum
Write a procedure to sum up all the values in
the nodes of a binary tree of integers

Solution: To find the sum of all values in a


binary tree, we can sum up the value of the

root node, with the sum of all values of the left


subtree, and the sum of all values of the right
subtree

Basis step: sum(nil) = 0


Recursive Step: sum(node) = node.value +

sum(node.left) + sum(node.right)

43
Binary Tree: Sum

roo
sum(root) = 8

t
+ sum(root.left)
+ sum(root.right)

right
left subtree
subtree
sum(root) = 8 sum(right) = 10
sum(left) = 3 +sum(root.left) +sum(right.left)
+sum(left.left) +sum(root.right)
+sum(right.right)
+sum(left.right)

44
Binary Tree: Sum
Basis step: sum(nil) = 0
Recursive Step: sum(node) = node.value +

sum(node.left) + sum(node.right)

procedure sum(BinaryTreeNode node)


if node = NIL then
return 0
else
return node.value + sum(node.left) +
sum(node.right)
{output is the sum of values in all nodes in the tree}
We call the procedure on the root of the tree:
sum(root)

45
Binary Tree: Number of Nodes
Write a procedure to counts the number of
nodes in a binary tree

Solution: To find the number of nodes in a


binary tree, we can sum up 1 (the root node)

with the total nodes of the right subtree and


the total nodes of the left subtree

Basis step: count(nil) = 0


Recursive Step: count(node) = 1 + count(node.left)

+ count(node.right)

46
Binary Tree: Number of Nodes
Basis step: count(nil) = 0
Recursive Step: count(node) = 1 + count(node.left) +

count(node.right)

procedure count(BinaryTreeNode node)


if node = NIL then
return 0
else
return 1+ count(node.left) +
count(node.right)
{output is the total number of nodes in the tree}

We call the procedure on the root of the tree: count(root)

47
Binary Tree: Height
Write a procedure to calculate the height of a
binary tree

The height of a binary tree represents the


number of levels of a given tree

Solution: To find the height of a binary tree, we


can add 1 (current height at root node) to the

max height of the two subtrees

Basis step: height(nil) = 0


Recursive Step: height(node) = 1 +

max(height(node.left), height(node.right))

48
Binary Tree: Height
Basis step: height(nil) = 0
Recursive Step: height(node) = 1 +

max(height(node.left), height(node.right))

procedure height(BinaryTreeNode node)


if node = NIL then
return 0
else
return 1+ max(height(node.left),
height(node.right))
{output is the height of the tree}

We call the procedure on the root of the tree:


height(root)
49
Any Questions?

50

You might also like