Reputation: 441
Here's my code:
#include <iostream>
using namespace std;
void reverse(int *, int);
int main()
{
const int len = 10;
int intArray[len] = {5, 6, 4, 1, 3, 10, 15, 13, 2, 7};
reverse(intArray, len);
}
void reverse(int intArray[], int len)
{
int j = len;
for(int i = 0; i < len; i++)
{
--j;
intArray[i] = intArray[j];
cout << intArray[i] << " ";
}
}
Then here is my output:
7 2 13 15 10 10 15 13 2 7
I see some examples of code doing the same thing, and I want to know why they all use a temp variable and if it is necessary?
Also, this question is a variation of an assignment MIT OCW. Though their assignment does not require the reversed array to be printed out, they want us to store the reversed values in the original array. But for some reason, their for loop only runs half the length? Here is their solution:
void reverse (int numbers [] , const int numbersLen )
{
for(int i = 0; i < numbersLen / 2; ++ i ) {
int tmp = numbers [ i ];
int indexFromEnd = numbersLen - i - 1;
numbers [ i ] = numbers [ indexFromEnd ];
numbers [ indexFromEnd ] = tmp ;
}
}
Upvotes: 0
Views: 111
Reputation: 161
Use the following for loop in the reverse function:
int tmp;
for (int i = 0; i < len / 2; i++)
{
--j;
tmp = intArray[j];
intArray[j] = intArray[i];
intArray[i] = tmp;
}
then print the array from a different loop.
Upvotes: 1
Reputation: 38757
For fun, trying manual reverse algorithm and output in a single loop.
void reverse(int intArray[], int len)
{
if (len <= 0)
return;
cout << intArray[len - 1] << " ";
if (len == 1)
return;
reverse(intArray + 1, len - 2);
int tmp = intArray[0];
cout << tmp << " ";
intArray[0] = intArray[len - 1];
intArray[len - 1] = tmp;
}
The tmp variable is necessary for a swap of two values. Otherwise, on first assignment (=) you would lose some data.
Upvotes: 0
Reputation: 70556
Just use the standard algorithm std::reverse
with the std::begin
and std::end
iterators
#include <algorithm>
#include <iostream>
int main()
{
const int len = 10;
int intArray[len] = {5, 6, 4, 1, 3, 10, 15, 13, 2, 7};
std::reverse(std::begin(intArray), std::end(intArray));
for (auto&& e : intArray)
std::cout << e << ", ";
}
If you have to write your own reverse algorithm, here's a possible implementation
template<class BidirIt>
void reverse(BidirIt first, BidirIt last)
{
while ((first != last) && (first != --last)) {
std::iter_swap(first++, last);
}
}
Here, std::iter_swap(a, b)
just calls std::swap(*a, *b)
. You can come up with your own swap of course.
It's recommended to have algorithms take iterator pairs so as to be compatible with the rest of the Standard Library.
Upvotes: 2
Reputation: 11216
You save all the "reversed" bytes into the same array overwriting original elements. Use another, empty array to save the result to.
If you need to use the same array, you would swap corresponding elements. For swapping you need the temporary variable and run the loop only half the length of the array.
Upvotes: 1