Aug 072012
 

We have already seen the problem to reverse the words in a string, in the solution to that problem we have also written function to reverse the string. That was a non-recursive (iterative) function. Write a recursive function to reverse the String.

For example: If the String is “ABCD” then the output should be “DCBA“.

Before getting to the solution, please note that a non-recursive solution is always better than a recursive solution in terms of its time and space complexities. To know more about recursion refer this post.

Algorithm:

Let n be the size of String
initially start = 0, end = n-1
Stop when start >= end
 - Swap the start and end elements in the string.
 - Call the function recursively with start+1, end-1

Code:

void recursiveReverse(char *str, int start, int end)
{
    if(start >= end)
        return;

    // Swapping element at start & end
    char temp = str[start];
    str[start]=str[end];
    str[end]=temp;
    recursiveReverse(str, start+1, end-1);
}

 

  One Response to “Recursive function to reverse a String”

Comments (1)
  1. awesome thanx a lot.it is very simple and easy to understand

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)