String reversal using recursion

In summary: Another way to think about recursion is as a tree, but not one where the nodes are functions, but where the nodes are local variables. This is because each recursive call needs its own space on the stack to store its local variables. So the tree would look something like this:local variables in reverse(str): str, out / \local variables in reverse(str(1:end-1)): str, out / \local variables in reverse(str(1:end-2)): str, outetc.But again, this is not the same as a tree of function calls.
  • #1
gfd43tg
Gold Member
950
50

Homework Statement


Write a function called reverse that uses recursion to reverse any one-dimensional string array.

Homework Equations


The Attempt at a Solution


Code:
function out = reverse(str)
if length(str) == 0
    out = str;
else
    out = [str(end) reverse(str(1:end-1))];
end

I am having difficulty understanding how this recursion tree will look. I am using a break point to understand the behavior, and it seems like every iteration it is taking off the last letter of the string until the string is empty, then it is filling it back in reverse order. But I can't put that into the form of a tree.
ImageUploadedByPhysics Forums1407566948.526315.jpg
 
Physics news on Phys.org
  • #2
There's a level of recursion for every element in the string (which consumes a lot of stack space). At the final depth of recursion, the function returns a null string. The next level up, returns the 1st element, the next level up returns the 2nd element followed by the 1st element, then 3rd element followed by (2nd, 1st), ...
 
  • #3
How should the tree of recursive calls look? Does my root node have correct children? I'm trying to do this based off a fibonacci sequence that I wrote recursively where each node had two children with fibnum(n-1) and fibnum(n-2), but that was easier to see on a tree. Now instead of a sum I am appending the end to the recursive function, so I am confused about how the tree should appear.
 
  • #4
It doesn't look right to me. Anyway, there is a trick you don't know about. How would you solve this problem: "Find a recursive procedure to print a string one character at a time." Try to solve that and then find an extremely simple way to modify it to print the string in reverse.
 
  • #5
The tree would look something like this:

Code:
//
     node
  end-0  node
      end-1  node
         end-2  node
           ...
                 2  node
                   1  node
                     0  null

Side note, recursively splitting the string into halves would be better (less stack space):
Code:
std::string rvrs(std::string str)
{
size_t m, n;
    if(str.size() < 2)
        return(str);
    m = str.size()/2;
    n = str.size()-m;
    std::string left  = rvrs(str.substr(0, m));
    std::string right = rvrs(str.substr(m, n));
    return(right + left);
}
 
  • #6
What you are labeling as node should be reverse(str(1:end-1)), or do the indices change there as well? Like the 2nd layer should be

Code:
 reverse(str)
         str(end) reverse(str(1:end-1))
               str(end-1) reverse(str(1:end-2))
                     ...
                                        str(1)    reverse(str(1:1))
 
  • #7
Maylis said:
What you are labeling as node should be reverse(str(1:end-1)), or do the indices change there as well?
Is the goal here to show what the tree looks like during calls or during returns? What I posted is a tree of returned values. The stack isn't really a tree, it's just a set of pointers to concatenated strings, so there's no "left" or "right" on the stack, but only in the concatenation operation performed within the recursive function.

The example code I posted does end up with left and right pointers on the stack, but no nodes, and it's a depth first, left first sequence, so again, it's not really a tree structure.
 
  • #8
I was under the impression that the tree looks identical to the calls as the returns, with the exception of how the tree is traversed. Calls are pre-order and returns are post-order, no??

In general I don't understand how to do the trees. My other thread I believe the tree is correct, with the likely exception of the route of traversal. Technically this question doesn't ask anything as far as how many recursive calls are made, I was just wondering out of my own understanding. Perhaps there is a reason that it wasn't asked, it might be something we didn't cover.
 
  • #9
In my opinion, the goal here should be looking at what is on the "call stack". Recursion nests local variables onto the stack, which normally is not considered to a tree structure (as far as I know). A call stack, may optionally include a linked list of "frame pointers", but that's optional (many compilers allow frame pointers to be omitted).

http://en.wikipedia.org/wiki/Call_stack
 

1. How does recursion work in string reversal?

Recursion is a programming technique where a function calls itself repeatedly until a certain condition is met. In the case of string reversal, the function calls itself with a smaller portion of the original string until the entire string is reversed.

2. Can you explain the base case in string reversal using recursion?

The base case in string reversal using recursion is the smallest unit of the string that cannot be broken down any further. This is usually when the string has only one character left, which is already in the correct position. Without a base case, the function would continue to call itself indefinitely.

3. How is memory managed in string reversal using recursion?

Recursion uses the call stack to keep track of function calls. When a function is called, its variables and parameters are stored on the stack. As each recursive call returns, those variables are popped off the stack. In the case of string reversal, the original string is not modified, and instead, a new reversed string is built using the recursive calls.

4. What are the advantages of using recursion for string reversal?

One advantage of using recursion for string reversal is that it can be written with a concise and elegant code. It also simplifies the problem into smaller subproblems, making it easier to understand and debug. Furthermore, recursion can be more efficient than other methods, such as using a loop, when dealing with large strings.

5. Are there any limitations to using recursion for string reversal?

One limitation of using recursion for string reversal is that it can be less efficient than other methods for small strings. This is because each recursive call involves extra overhead, such as pushing and popping from the call stack. Additionally, if the string is too long, it can cause a stack overflow error due to the limited size of the call stack.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
932
  • Engineering and Comp Sci Homework Help
Replies
11
Views
891
  • Engineering and Comp Sci Homework Help
Replies
12
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
935
  • Programming and Computer Science
Replies
17
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
1K
  • Programming and Computer Science
2
Replies
55
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
19K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
Back
Top