C++ Reverse function that reverses the characters in a string given two indices using recursive

This is the first time I am using this, as I usually find other people's questions on here but i can't seem to figure this one out. The problem states:

Using recursion, write a reverse function that reverses the characters in a string or character array given two indices (starting and ending). The string or the character array should reflect the reversal. Test by reading indices as input 11,18 (i.e. letters 12,19) and call the reverse function to reverse letters: 12-19

This is what I have so far:

string reverseFunction(string String, int indexStart, int indexEnd)
{
    if(indexStart != 0)
    {
        for (int i = indexStart; i < indexEnd; i++)
        {
             swap(String[i], String[indexEnd - i - 1]);
        }
    }
    else
    {
        for (int i = indexStart; i < indexEnd/2; i++)
        {
             swap(String[i], String[indexEnd - i - 1]);
        }
    }

    return String;
}

Any help is greatly appreciated. Thank you in advance!!

1 answer

  • answered 2018-09-15 23:44 MinhVP

    First, You have your index wrong, and I don't understand why you have to split cases between indexStart=0 and indexStart!=0 since it'll be worked the same way. What you need is something like this:

    for (int i = indexStart; i < (indexStart+indexEnd)/2; i++){
        swap(String[i], String[indexEnd-i+indexStart]);
    }
    

    (indexStart+indexEnd)/2 is the middle index of start index and end index, where you want to stop.

    Second, to use recursion you have to first identify your break condition. Let just say you run from indexStart, so you want to stop at the middle of it and indexEnd so stop at mid = (indexStart+indexEnd)/2. After that you take that mid and use it in the recursive function, something like:

    void reverseFunction(int indexStart, int indexEnd, int current, int stop){
        swap(String[current], String[indexEnd-current+indexStart]);
        if (current == stop) return;
        else reverseFunction(indexStart, indexEnd, current+1, stop);
    } 
    

    Recursion means you call a function within itself until it stops, that means you need a break condition (in this case current == stop) or else it will run forever, and some variables that will change through out your run until it meet the break condition (in this case the current variable). Between that is what you want to do (in this case, reverse the array).