What I want to do is:
change the array a[] = {1,2,3,4,5}
to a[] = {5,4,3,2,1}
by recursion

``````void reverse(int *a, int size){
if ( size == 0)
return;
int t = a[size-1];
a[size - 1] = *a;
*a = t;
reverse(a, size/2);
}``````

However, the above coding did not work
it only gave the result {5,3,2,4,1}
It seems that the pointer did not progress forward after I plus 1.
i.e. it can't move from a[0] to a[1] and so on...

3
Contributors
5
Replies
6
Views
8 Years
Discussion Span
Last Post by am5a03

Probably some thing of this sort

``````void rev(int* arr, int lower, int upper)
{
if ( lower >= upper)
return;

// Swap the 2 values
rev(arr, lower+1, upper-1);
}``````

Where lower and upper are the smallest and the largest indexes of the array

Probably some thing of this sort

``````void rev(int* arr, int lower, int upper)
{
if ( lower >= upper)
return;

// Swap the 2 values
rev(arr, lower+1, upper-1);
}``````

Where lower and upper are the smallest and the largest indexes of the array

Where are you changing the array?

``````void reverse(int *a, int size){
if (size == 0)
return;
cout << *a;
reverse(a+1, size-1);
}``````

It can successfully print out the array.
However, I found some weird thing in the DDD debugger.
After the first run
i.e.
reverse(a,5)
when it comes to the recursive call:
reverse(a+1,4), the value of *a is still fine, which is 2.
However, for the value int t, it becomes 1! which is not the value of a[4-1], I'm still searching the problem of the coding.

Edited by am5a03: n/a

@firstPerson

Where I have written swap the 2 variables that's where code has to be written to swap the 2 variables....I guess to remove ambiguity I should have written
write code to swap the 2 variables here

@am5a03

You dont want to break when the size=0, you want to break much before that ... Check out the code segment that I have posted.

:) thanks for you guys' help.
Finally I did it!

``````void reverse(int *a, int size){
if ( size <= 0)
return;
int t = a[size-1];
a[size - 1] = *a;
*a = t;
reverse(a+1, size-2);
}``````

Edited by am5a03: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.