Array Reversal

Started by
7 comments, last by NerdInHisShoe 16 years, 9 months ago
How would you take an array of ints and write them backwards: From: 5 7 9 2 0 | 1 | 2 | 3 To: 2 9 7 5 0 | 1 | 2 | 3 Thanks
James HammondUniversity of ColoradoDepartment of Computer Science
Advertisement
Most languages have this in their standard library. For instance, C++ has std::reverse.
Just iterate till the middle of the array and switch the elements with their corresponding elements of the end.

Example:

first step: switch 5 and 2
second step: switch 7 and 9

and so on...
www.bug-soft.net
Reading comprehension!!!

Quote:How would you take an array of ints and write them backwards:


Why do extra O(n) step, when we have an array.
Quote:Why do extra O(n) step, when we have an array.

My array may or not be full and with what I need to do with it it will be MUCH easier if I have them in reverse order.

My confusion comes in because the array might, and probably often will not be full.

James HammondUniversity of ColoradoDepartment of Computer Science
Quote:Original post by Hammonjj
Quote:Why do extra O(n) step, when we have an array.

My array may or not be full and with what I need to do with it it will be MUCH easier if I have them in reverse order.

My confusion comes in because the array might, and probably often will not be full.


Indeed, why an extra step:
int ARRAY_SIZE = 1000;int n= 77; // actual number of elements in arrayX array[ARRAY_SIZE];for ( int i = 0; i < n; i++ ) {  // forward traversal  array...}for ( int i = n-1; i >= 0; i-- ) {  // reverse traversal  array...}

And if you really, really need to reverse it... you couldn't think to do this yourself:

for (int i = 0; i < your_array_size / 2; ++i){    int temp = your_array;    your_array = your_array[your_array_size - i - 1];    your_array[your_array_size - i - 1] = temp;}


Of course, std::reverse will do this in a generic way for you. I mean, it's already there. Use it!

// note: I've never used std::reverse, but my guess would be this:std::reverse(your_array, your_array + your_array_size);


Hope that helps!
[ search: google ][ programming: msdn | boost | opengl ][ languages: nihongo ]
/** * Program that takes an array of ints and writes it backwards. */#include <algorithm>#include <iostream>#include <iterator>using namespace std;int array[] = { 5, 7, 9, 2 };int main(){  reverse_copy(array,	       array + sizeof(array) / sizeof(int),               ostream_iterator<int>(cout, " "));  cout << "\n";}

Stephen M. Webb
Professional Free Software Developer

This is a fun little exercise, heh, here's my function:

void areversal(int *ara, int n){        int i;        for(i=0; i<n/2; i++)        {                ara+=ara[n-1-i];                ara[n-1-i]=ara-ara[n-1-i];                ara-=ara[n-1-i];        }}
Johnny was a chemist's son by Johnny is no more, for what Johnny thought was H2O was HO4

This topic is closed to new replies.

Advertisement