Page 1 of 1

Reversing an integer array

Posted: Sat Jan 03, 2004 8:51 pm
by chris
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

Posted: Sat Jan 03, 2004 10:20 pm
by sonneveld
can't you just go

Code: Select all

#include <algorithm>

int myarray[10];
reverse(myarray, myarray+10);
gotta love the STL. Course this is assuming you're using C++ in the first place.

- Nick

Re:Reversing an integer array

Posted: Sun Jan 04, 2004 8:49 am
by chris
Err sorry I forgot this was "General Programming". I'm working in C.

Re:Reversing an integer array

Posted: Sun Jan 04, 2004 9:44 am
by Tim
How about this:

Code: Select all

for (i = 0; i < length / 2; i++)
    swap(a + i, a + length - 1 - i);
Or if you want to create a reversed copy:

Code: Select all

for (i = 0; i < length; i++)
    b[i] = a[i + length - 1];

Re:Reversing an integer array

Posted: Sun Jan 04, 2004 10:14 am
by chris
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;
   }