Recursion - Writing A Recursive Function - Recursion Rules
Recursion - Writing A Recursive Function - Recursion Rules
Lecture #8
• Recursion
• Writing a recursive function
• Recursion Rules
2
Recursion
So pay attention!
4
Just return
Is the problem trivially solved Yes
the answer
No
Break the problem into two
or more simpler sub-problems
SolveAProblem(sub-problem1)
Solve each sub-problem j SomeOtherFunction(sub-problem1)
...
bybycalling
callingsome
ourself!
other SolveAProblem(sub-problem )
SomeOtherFunction(sub-problemn)
n
6 17 22 3 14 95
6
6 17 22 3 14 95
Lazy Person’s
If you’re Sort:
handed just one card, then just give it right back.
Split the cards into two roughly-equal piles
nerdy student
Hand one pile to student Asay
A and askand ask
them
“do them
to
the sorttoit
Lazy sort it Sort”
Person’s
Hand the other pile to nerdy student B and ask say them
“do theto Lazy
sort Person’s
it Sort”
Take the two sorted piles and merge them into a single sorted pile
9
When you Ok
add– the
but code
wouldtoyou agree
make it definitely
a function works you
call itself, if we
need to
have faith that thatchange
call willthe algorithm
work properlylike
(onthis?
the subset of data).
If we can rely upon OtherSort to somehow properly sort each sub-array,
It takes somethat
we agree timeourto udpated
learn to MergeSort
think in thiswill
way, but Correct?
work. once you
“get it,” you’ll be a programming Great!
10
Simplifying Step:
Every time a recursive function calls itself, it must pass
in a smaller sub-problem that ensures the algorithm will
eventually reach its stopping condition.
Step #1:
Write the function header
Let’s use these steps
Step #2: to write a recursive
Define your magic function function to calculate
Step #3: factorials.
Add your base case code
Step #4: Recall, the definition of
Solve the problem w/the magic function fact(N) is:
result = fact( n );
}
15
Thenfigure
Let’s our out
new function
a way will of
to solve each int main()
work
thesecorrectly! {
sub-problems.
int n = 6, result;
// use magicfact to solve subproblems
Cool! Now we can combine the results result = magicfact( n-1 );
of our sub-problems to get the
overall result! }
18
Wait
But if our afunction
second! calls
Ouritself,
magicfact
what
function basically // provided for your use!
stops it from runningjust calls fact!
on forever? int fact(int n)
{int magicfact(int x) { … }
That
Right! Ourmeans
base that
case fact
code is really
ensures int fact(int n)
just calling itself! stops { // don’t worry about how your
that our function eventually //
calling itself! if function
(n == 0) will actually work!
// we’ll figure
return 1; //that
baseout later!!
case
The magicfact function hid this from
us, but that’s what’s really happening! int part1 = n;
} int part2 = magic fact( n-1 );
Let’s replace our call(s) to the magic
return part1 * part2;
function with calls directly to our }
own function.
int main()
{
int n = 6, result;
// use magicfact to solve subproblems
result = magicfact( n-1 );
}
19
Factorial Trace-through
int fact(int n) n 0
{ 0 == 0
if (n == 0)
1
return (1);
return(n * fact(n-1));
}
int fact(int n) n 1
{ 1 == 0
if (n == 0)
return (1);
return(n * 1*1=1
1 0
fact(n-1));
} result 2
int fact(int n) n 2 int main()
{ 2 == 0 {
if (n == 0)
int result;
return (1);
2
result = fact(2);
return(n * 2*1=2
1
2
fact(n-1)); cout << result;
} }
21
arr 10 20 70 14 39
0 n-1
22
You could also have written:
Step #1: Write the function header int *arr
It’s the same thing!
Figure out what argument(s) your
function will take and what it needs
to return (if anything).
int sumArr(int arr[ ], int n)
To sum up all of the items in an array, we {
}
23
}
24
}
25
Step #4: Solve the problem using the magic function
Now try to figure out how to use the // provided for your use!
magic function in your new function to int magicsumArr(int arr[], int x) { … }
help you solve the problem.
int sumArr(int arr[ ], int n)
Unfortunately, you can’t use the magic {
function to do all the work for you… if (n == 0) return 0;
(it can’t solve problems of size n)
if (n == 1) return arr[0];
So let’s try to break our problem into two int s = magicsumArr( arr, n );
(or more) simpler sub-problems and use our
magic function to solve those. return s;
}
int main()
{
const int n = 5;
int arr[n] = { 10, 100, 42, 72, 16}, s;
s = magicsumArr( arr, n-1 ); // first n-1
s = magicsumArr( arr+1, n-1 ); // last n-1
s = magicsumArr( arr, n/2 ); // sums 1 half
st
}
26
Step #4: Solve the problem using the magic function
Now try to figure out how to use the // provided for your use!
magic function in your new function to int magicsumArr(int arr[], int x) { … }
help you solve the problem.
int sumArr(int arr[ ], int n)
Unfortunately, you can’t use the magic {
Hopefully,
function to dowe all can agree
the work for you… if (n == 0) return 0;
(itif
that can’t
the solve problems
magic of size n)
function if (n == 1) return arr[0];
does
So what
let’s try it’s supposed
to break our problem into two int front =
(or more) simplerto…sub-problems and use our int total = front + arr[n-1];
magic function to solve those.
return total;
}
Then our new function will
Strategy #1: Front to back int main()
work correctly! {
Your function uses the magic function
const int n = 5;
to process the first n-1 elements of
int arr[n] = { 10, 100, 42, 72, 16}, s;
the array, ignoring the last element.
s = magicsumArr( arr, n-1 ); // first n-1
Once it gets the result from the magic
function, it combines it with the last s = magicsumArr( arr+1, n-1 ); // last n-1
element in the array. s = magicsumArr( arr, n/2 ); // sums 1 half
st
}
29
int magicsumArr(int arr[], int x)
{ Step #5: Remove the magic
return sumArr(arr,x);
But
} if our function calls itself, what // provided for your use!
stops it from running on forever? int magicsumArr(int arr[], int x) { … }
OK, so let’s see what this magic
Right!function
Our basereally
case looks like!
code ensures int sumArr(int arr[ ], int n)
{
that
Waitour functionOur
a second! eventually stops
magicsumArr if (n == 0) return 0;
calling
function just itself!
calls sumArr! if (n == 1) return arr[0];
This means that sumArr is really int first = magic sumArr( arr, n/2 );
just calling itself! int scnd = magic sumArr( arr+n/2,
n – n/2 );
The magic function hid this from us, return first + scnd;
}
but that’s what’s really happening!
int main()
{
OK, well in that case, let’s replace const int n = 5;
our calls to the magic function with int arr[n] = { 10, 100, 42, 72, 16}, s;
calls directly to our own function.
s = magicsumArr( arr, n-1 ); // first n-1
Will that work? Yup! s = magicsumArr( arr+1, n-1 ); // last n-1
s = magicsumArr( arr, n/2 ); // sums 1 half
Woohoo! We’ve just created our
st
}
30
Array-summer Trace-through
int sumArr(int arr[], int n)
{
if (n == 0) return 0; 42
20
if (n == 1) return arr[0];
int first = sumArr( arr, n/2 );
int sumArr(int arr[], int n) int scnd = sumArr( arr+n/2, n-n/2);
{
if (n == 0) return 0; 10 return first + scnd;
}
if (n == 1) return arr[0];
20 1
n/2 );1
int first = sumArr( arr,42
int scnd = sumArr( arr+n/2, n-n/2);
return first62
+ scnd;
}
int main()
int sumArr(int arr[], int n) {
{
const int n = 3;
if (n == 0) return 0;
int nums[n] = { 10, 20, 42 };
if (n == 1) return arr[0];
10 1
int first = sumArr( 20arr, 42
n/2 ); 2 nums 10 20 42
3
int scnd = sumArr( arr+n/2, n-n/2);
return first72+ scnd; cout << sumArr( nums , n );
} }
32
Step #1:
Write the function header
Step #2:
Define your magic function
Step #3:
Add your base case code
Step #4:
Solve the problem w/the magic function
Step #5:
Remove the magic
Step #6:
Validate your function
Solve this problem and Get Bonus marks in mid term