Recursion in C-2
Recursion in C-2
What is recursion?
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
Problems defined recursively
• There are many problems whose solution
can be defined recursively
Example: n factorial
1 if n = 0
n!= (recursive solution)
(n-1)!*n if n > 0
1 if n = 0
n!= (closed form solution)
1*2*3*…*(n-1)*nif n > 0
Coding the factorial function
• Recursive implementation
int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
Coding the factorial function
(cont.)
• Iterative implementation
int Factorial(int n)
{
int fact = 1;
return fact;
}
Recursion vs. iteration
• Iteration can be used in place of recursion
– An iterative algorithm uses a looping construct
– A recursive algorithm uses a branching structure
• Recursive solutions are often less efficient, in
terms of both time and space, than iterative
solutions
• Recursion can simplify the solution of a problem,
often resulting in shorter, more easily understood
source code
How do I write a
recursive function?
• Determine the size factor
• Determine the base case(s)
(the one for which you know the answer)
• Determine the general case(s)
(the one where the problem is expressed as a
smaller version of itself)
• Verify the algorithm
(use the "Three-Question-Method")
Recursive binary search
• Non-recursive implementation
template<class ItemType>
void SortedType<ItemType>::RetrieveItem(ItemType& item, bool& found)
{
int midPoint;
int first = 0;
int last = length - 1;
found = false;
while( (first <= last) && !found) {
midPoint = (first + last) / 2;
if (item < info[midPoint])
last = midPoint - 1;
else if(item > info[midPoint])
first = midPoint + 1;
else {
found = true;
item = info[midPoint];
}
}
Recursive binary search (cont’d)
template<class ItemType>
bool BinarySearch(ItemType info[], ItemType& item, int first, int last)
{
int midPoint;
if(first > last) // base case 1
return false;
else {
midPoint = (first + last)/2;
if(item < info[midPoint])
return BinarySearch(info, item, first, midPoint-1);
else if (item == info[midPoint]) { // base case 2
item = info[midPoint];
return true;
}
else
return BinarySearch(info, item, midPoint+1, last);
}
}
How is recursion implemented?
int b(int x)
{
int z,y;
……………… // other statements
z = a(x) + y;
return z;
}
What happens when a function is
called? (cont.)
int f(int x)
{
int y;
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
2*f(2)
2*f(1)
2*f(1)
=f(0)
=f(1)
=f(2)
=f(3)
Deciding whether to use a
recursive solution
• When the depth of recursive calls is
relatively "shallow"
• The recursive version does about the same
amount of work as the nonrecursive version
• The recursive version is shorter and simpler
than the nonrecursive solution