Proud Member
Proud Member

Reputation: 40496

Is there an efficient and secure way to reverse all elements in an array?

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?

Upvotes: 0

Views: 3779

Answers (4)

Aditya Sharma
Aditya Sharma

Reputation: 1

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;

}

Upvotes: 0

Christian Stieber
Christian Stieber

Reputation: 12496

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

Upvotes: 2

perilbrain
perilbrain

Reputation: 8207

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 .

Upvotes: 3

dana
dana

Reputation: 18145

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

Upvotes: 8

Related Questions