Recursive function to reverse an array

Jul 27, 2012 at 1:36pm
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;
}
Jul 27, 2012 at 1:48pm
use std::swap from the header <algorithm>
EDIT: Why on Earth would you use POINTERS????
Last edited on Jul 27, 2012 at 1:50pm
Jul 27, 2012 at 1:53pm
Why on Earth would you use POINTERS????

O.o
Jul 27, 2012 at 2:05pm
I don't like using pointers, but this question is a homework practice, for recursion
Jul 27, 2012 at 2:23pm
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.
Jul 27, 2012 at 3:12pm
> 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 ) ;
}
Jul 27, 2012 at 11:56pm
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;
}
Jul 28, 2012 at 6:55am
I wonder ... instead of using int n couldn't you just check to see if *s == '\0' ?
Last edited on Jul 28, 2012 at 6:57am
Jul 28, 2012 at 8:22am

@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 Jul 28, 2012 at 8:23am
Jul 31, 2012 at 9:00am
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 Jul 31, 2012 at 9:01am
Topic archived. No new replies allowed.