0

I need to reverse large arrays such that the first element becomes the last, and the last becomes the first.

Until now I did this by creating a copy of this array, then iterate backwards over the original and write to the copy. After that, write the copy back to the original.

Is it possible to do this safely in one single loop by simultaneous access to the first and last element, storing one of them in a temp var and swapping the values?

Proud Member
  • 40,078
  • 47
  • 146
  • 231
  • yeah pretty much your last sentence will accomplish what you want. You'll need a temp value, and 2 counters (1 from back 1 from front). – twain249 Aug 19 '12 at 16:38
  • Likely duplicate of http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c. The best answer there IMHO is http://stackoverflow.com/a/199891/831878 – Ray Toal Aug 19 '12 at 16:49

4 Answers4

8

Likely the most efficient way is using an in-place algorithm, such as the one below (which is equivalent to that from the Wikipedia article here):

for (int ix = 0; ix < len / 2; ix++) {
    int t = arr[ix];
    arr[ix] = arr[len - ix - 1];
    arr[len - ix - 1] = t;
}
obataku
  • 29,212
  • 3
  • 44
  • 57
dana
  • 17,267
  • 6
  • 64
  • 88
3

For integer types a better way is...

int arr[5]={1,2,3,4,5};
int c=0,d=sizeof(arr)/sizeof(*arr)-1;
for(;c<d;c++)
{  
 arr[c] ^= arr[d-c];
 arr[d-c] ^= arr[c];
 arr[c] ^= arr[d-c];
}

since XOR is one byte instruction, it will take hardly 3 byte along the swap line .

perilbrain
  • 7,961
  • 2
  • 27
  • 35
  • 1
    @Jens:- was about to edit, but these government network providers...I would rather smash their heads someday .... – perilbrain Aug 19 '12 at 17:21
2
int Array[100];

unsigned int i, j;
for (i=0, j=100-1; i<j; i++, j--)
{
   int t;
   t = Array[j];
   Array[j] = Array[i];
   Array[i] = t;
}
Peter Varo
  • 11,726
  • 7
  • 55
  • 77
Christian Stieber
  • 9,954
  • 24
  • 23
  • Looks similar to http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c/199891#199891 - which worked perfectly. – Proud Member Aug 19 '12 at 18:04
0

You can use reverse() function or I think this will be very easy solution

#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
unsigned int arr[n];
for(int i = 0; i < n; i++)
{
    cin>>arr[i];
}
while(n)
{
    cout<<arr[n-1]<<" ";
    n--;
}
return 0;

}