Reversing an integer array

Programming, for all ages and all languages.
Post Reply
chris

Reversing an integer array

Post 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?
sonneveld

Re:Reversing an integer array

Post 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
chris

Re:Reversing an integer array

Post by chris »

Err sorry I forgot this was "General Programming". I'm working in C.
Tim

Re:Reversing an integer array

Post 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];
chris

Re:Reversing an integer array

Post 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;
   }

Post Reply