Reversing an integer array
Reversing an integer array
I've been trying to reverse an array for the last little while and I can't seem to get it right. Has anybody done this before?
Re:Reversing an integer array
can't you just go
gotta love the STL. Course this is assuming you're using C++ in the first place.
- Nick
Code: Select all
#include <algorithm>
int myarray[10];
reverse(myarray, myarray+10);
- Nick
Re:Reversing an integer array
Err sorry I forgot this was "General Programming". I'm working in C.
Re:Reversing an integer array
How about this:
Or if you want to create a reversed copy:
Code: Select all
for (i = 0; i < length / 2; i++)
swap(a + i, a + length - 1 - i);
Code: Select all
for (i = 0; i < length; i++)
b[i] = a[i + length - 1];
Re:Reversing an integer array
This is what I ended up with. I'm pretty sure it works, i've tested it with a bunch of different sized arrays.
Code: Select all
for (i = 0; i < (length / 2); i++) {
tmp = a[i];
a[i] = a[length - (i+1)];
a[length - (i+1)] = tmp;
}