Array Reversal
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
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...
Example:
first step: switch 5 and 2
second step: switch 7 and 9
and so on...
Reading comprehension!!!
Why do extra O(n) step, when we have an array.
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.
Quote:Original post by HammonjjQuote: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:
Of course, std::reverse will do this in a generic way for you. I mean, it's already there. Use it!
Hope that helps!
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!
/** * 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";}
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]; }}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement