Recursion is a wonderful method that saves lots of code writing. So what's new in this post ? I haven't found any proper explanation of how exactly to write a recursive algorithm, what are the modules to be considered in a recursive algorithm or what is the fastest way to understand recursion. When I started developing a quick sort algorithm it took eternity to write my own code without reference. So here is the division
Recursive program has four parts
1. Base case which is the end point where recursion will stop or recursion will boomerang back.
Else case
2. Separate (based on number of recursions)
3. Recurse
4. Merge into one
example, take this code
------
int x = 0;
x = 10;
factorial(x);
public void factorial(int x)
{
if(x == 1)
return x;
else
return x*factorial(x-1);
}
------
is the usual way, but since there is not data manipulation or division, separate and merge don't make sense here.
Dividing this function as per what I have pointed it looks like this ,
------
public void factorial(int x)
{
// base case
if(x == 1)
return x;
// else case
else
{
// separate
int y = x -1;
// recurse
y = factorial(y);
// merge
x = x * y;
return x;
}
}
------
This is the worst case we can get with memory in case we want to make some more operations on y based on the algorithm.
No comments:
Post a Comment