Check if one string is rotation of another
July 31, 2012
Blue Eyed Islanders puzzle
August 7, 2012

Recursive function to reverse a String

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);
}

 

1 Comment

  1. Ravi says:

    awesome thanx a lot.it is very simple and easy to understand

Leave a Reply

Your email address will not be published. Required fields are marked *