Recursive function to reverse an array

Wish to know how to reverse an array recursively. My code is definitely a mess. Best if a solution is pass by pointers as my main program too.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cstring>
using namespace std;
void reverse(char*p1, char*p2, int n = 0)
{
    if(p2 > p1)
    {
        return ;
    }

    else
    {
        //swap??
        char* temp = p1;
        p1 = p2;
        p2 = temp;

        cout << "p1 = " << p1 << "p2 = " << p2 << endl;

        reverse(p1-n+1,p2-n-1);
    }
}

int main()
{
    char str[] = "Hello";
    cout << str << endl;
    reverse(&str[0], &str[strlen(str) - 1]);
    cout << str << endl;
}
use std::swap from the header <algorithm>
EDIT: Why on Earth would you use POINTERS????
Last edited on
Why on Earth would you use POINTERS????

O.o
I don't like using pointers, but this question is a homework practice, for recursion
Pointers are a pretty big part of programming, I'd start learning to like them. They aren't some mysterious magical device used to confuse you, they're used all over the place in computers.
> Best if a solution is pass by pointers

You don't need that int n = 0, do you?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <algorithm>

void reverse( char* first, char* last )
{
    if( first < last )
    {
        std::swap( *first, *last ) ;
        reverse( first+1, last-1 ) ;
    }
}

int main()
{
    char cstr[] = "hello world!" ;
    reverse( cstr, cstr + sizeof(cstr) - 2 ) ;
}
Another realization of the function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
include <iostream>
#include <cstring>

using namespace std;

void reverse( char *s, int n )
{
    if (  n < 2 )
    {
        return ;
    }


    char c = s[0];
    s[0] = s[n-1];
    s[n-1] = c;

    reverse( ++s, --n );
}

int main()
{
    char str[] = "Hello";
    cout << str << endl;
    reverse( str, strlen( str ) );
    cout << str << endl;
}
I wonder ... instead of using int n couldn't you just check to see if *s == '\0' ?
Last edited on

@TwoOfDiamonds

I wonder ... instead of using int n couldn't you just check to see if *s == '\0' ?


It is possible only for the first recursive iteration. And what about subsequent iterations?!



Last edited on
Thanks for every answers given. Like what I said my code is a mess that int n=0 is just a code that I reference from other questions.
Last edited on
Topic archived. No new replies allowed.