Reverse an array in C++

In this post, we will see how to reverse an array in C++.


1. reverse() method

The recommended solution for reversing elements of the specified array is to use reverse() method defined in the algorithm header file.


Download   Run Code


2. In-place implementation

The standard solution is to read the elements from both ends of the array and swap them. This is done in-place as demonstrated below:


Download   Run Code


3. Using Stack

Another plausible way of reversing an array is to use the stack data structure. The idea is to push each element in the array into a stack. Then we simply pop values from the stack one by one and assign each popped item back to the original array starting from the beginning.


Download   Run Code


4. Using Recursion

We can also use recursion for reversing an array. The logic remains same as the in-place implementation discussed earlier, but it requires O(n) extra space for the call stack.


Download   Run Code

Following is another recursive program which stores elements of the array into the recursion call stack, and then put them back into the array in correct order when the recursion unfolds.


Download   Run Code

5. Using auxiliary array

Finally we can create an auxiliary array of same type and size as the input array, fill it with elements from original array in reverse order, and then copy the contents of the auxiliary array into the original one.


Download   Run Code

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of