12 2Recursion Final
12 2Recursion Final
Kumkum Saxena
Recursion
◼ What is Recursion?
◼ In plain English:
◼ Recursion: the process a procedure goes through,
when one of the steps of the procedure involves
rerunning the entire procedure
▪ Example: say that some procedure has 4 steps
▪ The 3rd step instructs you to run the entire procedure again
▪ Each time you get to the third step, you have to start anew
▪ This goes on, potentially, infinitely
▪ And this is an example of Recursion
◼ Note:
◼ This could go on for infinity as function A keeps calling
function A
▪ So we must have a way to exit the function!
Kumkum Saxena Recursion page 4
Recursion Example w/o terminate
◼ Example of recursion without a terminating
condition. Just keeps going and going and…
#include <stdio.h>
int main() {
print(); // Here we call the cheesy function
system("PAUSE");
return 0;
}
void print() {
int main(void) {
int i;
for (i = 10; i > 0; --i)
printf(“%d! ”, i);
printf(“\nBLAST OFF!\n”);
}
count_down(1)
▪ This mini program will print “1!”
▪ Cuz, again, 1 is greater than 0
▪ And then it calls count_down(0)
◼ What happens now?
▪ Execution does NOT flow into the IF statement
▪ 0 is NOT greater than 0
▪ So execution goes into the ELSE statement
▪ BLAST OFF! is printed
▪ This mini program has finished
▪ AND all the other function calls have finished
▪ Control returns to the main program and the program ends.
Kumkum Saxena Recursion page 10
Recursion
◼ Here’s what’s going on…in pictures
#include <stdio.h> count_down(10) Think of this as
Prints 10!
count_down(9)
calls count_down(9) your function stack
void count_down(int n); Prints 9!
callscount_down(8)
count_down(8)
Prints 8!
int main(void) { callscount_down(7)
count_down(7)
Prints 7!
count_down(10); callscount_down(6)
count_down(6)
Prints 6!
return 0; callscount_down(5)
count_down(5)
} Prints 5!
callscount_down(4)
count_down(4)
Prints 4!
callscount_down(3)
count_down(3)
Prints 3!
callscount_down(2)
count_down(2)
Prints 2!
callscount_down(1)
count_down(1)
Prints 1!
count_down(0)
calls count_down(0)
◼ The Output: Prints BLAST OFF!
◼ 10! 9! 8! 7! 6! 5! 4! 3! 2! 1!
BLAST OFF!
int fact(int n)
{ Straightforward Result:
int p, j; ex: n=3
p = 1;
for ( j=n; j>=1; j--) p = 1*3 // p = 3
p = p* j; p = 3*2 // p = 6
return ( p ); p = 6*1 // p = 6
}
this?
▪ This is really the hardest part
◼ You MUST figure out how you can think of the
problem in a recursive manner.
▪ Ask yourself: how can we rewrite this problem so
that it is defined recursively?
◼ Remember, we said that recursion:
▪ solves large problems by reducing them to
smaller problems of the same form
Kumkum Saxena Recursion page 14
Recursion - Factorial
◼ Example: Compute Factorial of a Number
◼ Recursive Solution
◼ Mathematically, factorial is already defined recursively
▪ Note that each factorial is related to a factorial of the
next smaller integer
◼ 4! = 4*3*2*1 = 4 * (4-1)! = 4 * (3!)
◼ Right?
◼ Another example:
◼ 10! = 10*9*8*7*6*5*4*3*2*1
This is clear right?
◼ 10! = 10*(9!) Since 9! clearly is equal to
9*8*7*6*5*4*3*2*1
Winding phase
Invoking/calling ‘itself’ to solve
smaller or simpler instance(s) of
a problem …
… and then building up the
answer(s) of the simpler
instance(s).
Unwinding phase
Unwinding: 2 * f(1) 1
f(0): Return 1
1 * f(0) 1
f(1): Return 1 * f(0) = 1 * 1 = 1
f(2): Return 2 * f(1) = 2 * 1 = 2
f(3): Return 3 * f(2) = 3 * 2 = 6
fib(5)
3 2
fib(4) fib(3)
2 1 1 1
fib(3) fib(2) fib(2) fib(1)
1 1 1 0 1 0
1 0
fib(1) fib(0)
f(0)
else else
return n * factorial(n-1); return fib(n-1) + fib(n-2);
} }
▪ Example: factorial(3) n
0
n n 1 n
1 1 1
n n n n 1
2 2 2 2
n n n n n
3 3 3 3 3
Kumkum Saxena
Recursion
◼ What is Recursion? From the programming
perspective:
◼ Recursion solves large problems by reducing
them to smaller problems of the same form
◼ Recursion is a function that invokes itself
◼ Basically splits a problem into one or more SIMPLER
versions of itself
◼ And we must have a way of stopping the recursion
◼ So the function must have some sort of calls or
conditional statements that can actually terminate the
function
if (terminating condition) {
DO FINAL ACTION
}
else {
Take one step closer to terminating condition
Call function RECURSIVELY on smaller subproblem
}
if (!(terminating condition) ) {
Take a step closer to terminating condition
Call function RECURSIVELY on smaller subproblem
}
◼ REMEMBER:
◼ We want a function that solves this same problem
◼ But we want that problem to be recursive:
▪ It should solve f(n) by reducing it to a smaller problem, but of
the same form
◼ Just like the factorial example: n! = n * (n-1)!
▪ (n-1)! was a smaller form of n!
◼ So think, what is a “smaller form” of our function, f(n)
Kumkum Saxena Recursion page 46
Recursion: General Structure
◼ Example using Construct 1
◼ Our function:
◼ Using n as the input, we define the following function
▪ f(n) = 1 + 2 + 3 + … + n
if (terminating condition) {
DO FINAL ACTION
}
else {
Take one step closer to terminating condition
Call function RECURSIVELY on smaller subproblem
}
if ( n == 0 )
return 0;
else
return (n + sumNumbers(n-1));
}
if (terminating condition) {
DO FINAL ACTION
}
else {
Take one step closer to terminating condition
Call function RECURSIVELY on smaller subproblem
}
if ( exponent == 0 )
return 1;
else
return (base*Power(base, exponent-1));
}
if (!(terminating condition) ) {
Take a step closer to terminating condition
Call function RECURSIVELY on smaller subproblem
}
start 1
2 3
void main() {
int disk;
int moves;
printf("Enter the # of disks you want to play with:");
scanf("%d",&disk);
// Print out the # of moves required
moves = pow(2,disk)-1;
printf("\nThe No of moves required is=%d \n",moves);
// Initiate the recursion
moveDisks(disk,'A','C','B');
}
Kumkum Saxena Recursion page 75
Recursion – Towers of Hanoi
◼ Towers of Hanoi:
◼ Solution:
void moveDisks(int n, char start, char finish, char temp) {
if (n == 1) {
printf(“Move Disk from %c to %c\n”, start, finish);
}
else {
moveDisks(n-1, start, temp, finish);
printf(“Move Disk from %c to %c\n”, start, finish);
moveDisks(n-1, temp, finish, start);
}
}
Kumkum Saxena
Binary Search
◼ Array Search
◼ We are given the following sorted array:
index 0 1 2 3 4 5 6 7 8
value 2 6 19 27 33 37 38 41 118
return 0;
}
Kumkum Saxena Recursion page 81
Binary Search
◼ Binary Search code:
◼ At the end of each array iteration, all we do is
update either low or high
◼ This modifies our search region
◼ Essentially halving it
◼ As we saw previously, this runs in log n time
◼ So when do we stop:
1) When the number is found!
2) Or when the search range is nothing
◼ huh?
◼ The search range is empty when (low > high)