|
-
October 15th, 2008, 03:28 AM
#1
convert Recursion to linear can it be done ?
Hello all
i have legacy code that preform Recursion calling this Recursion is very heavy and long and sometimes it gives me stack overflow exceptions
i wander in general or algorithmic view can i convert Recursion flow to linear ( not Recursion) ?
Thanks
-
October 15th, 2008, 04:12 AM
#2
Re: convert Recursion to linear can it be done ?
You can ALWAYS convert a recursive algorithm to a "non-recursive" one using a Stack to simulate the recursive calls. Each Stack element is a struct / class which will hold all the recursive call parameters data for one recursive call, this way you can handle the recursion yourself and without using the call stack, since your stack will allocate memory from the heap.
Regards,
Zachm
-
October 15th, 2008, 06:53 AM
#3
Re: convert Recursion to linear can it be done ?
Thanks for the reply
could you please point me to some code example
Thanks
-
October 15th, 2008, 08:02 AM
#4
Re: convert Recursion to linear can it be done ?
 Originally Posted by umen
Thanks for the reply
could you please point me to some code example
Thanks
Code:
int Sum(int x)
{
if (x > 1)
return x + Sum(x-1);
else
return 1;
}
int Sum(int x)
{
int z = 0;
for (int i=1; i<=x; ++i)
z+=i;
return z;
}
int Sum(int x)
{
std::stack<int> parts;
for (int i=1; i<=x; ++i)
{
parts.push(i);
}
int z = 0;
while (!parts.empty())
{
z += parts.pop();
}
return z;
}
[/code]
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|