Reputation: 87
I'm trying to reverse an int array using pointer incrementing/decrementing. When I run it, it reverses to the halfway point in the array, and then stops and goes backwards.
This is the result that I'm currently getting:
Array size: 10
Original array:
42 68 35 1 70
25 79 59 63 65
Reversed array:
65 63 59 79 25
25 79 59 63 65
Expected outcome:
65 63 59 79 25
70 1 35 68 42
This is the algorithm I'm using:
int temp = 0;
lastElement = &data[size - 1];
for (int i = 0; i < size; i++)
{
*(data) = *(lastElement);
data++;
lastElement--;
}
EDIT:
Working algorithm:
first = data;
last = &data[size - 1];
for (int i = 0; i < size / 2; i++)
{
int temp = *first;
*first = *last;
*last = temp;
first++;
last--;
}
Upvotes: 1
Views: 112
Reputation: 37512
I recommend to get familiar with STL
, especially STL algorithms.
There is reverse algorithm (see linked documentation with nice example).
Upvotes: 1
Reputation: 669
Change the for loop to be something like this:
for (int i = 0; i < size / 2; i++)
{
std::swap(*data, *lastElement);
data++;
lastElement--;
}
Upvotes: 0
Reputation: 7743
As your algorithm uses pointers at beginning and end of array, so each step of the loop swaps two elements. Thus your loop should have array size/2
steps (middle element if any stays in the current position).
first= data;
last = &data[size - 1];
for (int i = 0; i < size/2; i++)
{
int temp = *first;
*first = *last;
*last = temp;
first++;
last--;
}
Upvotes: 1
Reputation: 182743
If you swap half of an array for the other half, you've swapped the entire array. If you swap the first half for the second half and then swap the second half with the first half, you're back where you started. Don't do that.
Upvotes: 3