CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Aug 2006
    Posts
    230

    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

  2. #2
    Join Date
    Oct 2006
    Posts
    616

    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

  3. #3
    Join Date
    Aug 2006
    Posts
    230

    Re: convert Recursion to linear can it be done ?

    Thanks for the reply
    could you please point me to some code example
    Thanks

  4. #4
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: convert Recursion to linear can it be done ?

    Quote 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
  •  





Click Here to Expand Forum to Full Width

Featured