Summary: In this tutorial, we will learn different ways to reverse an array in C++ programming language.

Example:

There are multiple ways to reverse an array in C++. Let’s discuss each of them.

Method 1: Using an Extra Array

The idea is to create a new array and assign elements to it from the input array in reversed order.

To do this, we simply have to:

  1. Initialize an array with values.
  2. Declare a new empty array of the same size.
  3. Loop from the back of the input array and assign its elements to the new array.
  4. Output the reverse array.

Here is implementation of it in C++:

Output:

3, 2, 6, 5

Method 2: Without using an Extra Array

The logic to reverse an array without using another array in C++ is to swap 1st element with the last element, then the 2nd element with the 2nd last element, then 3rd, 4th… until we reach the middle element.

Reverse array without array

Output:

9 3 1 5 4

We used ‘i’ and ‘j’ to store the index of elements that needed to be swapped.

Inside while loop, we increment ‘i’ (i++) and decrement ‘j’ (j--), until j exceeds i.

In this method, we have not used any auxiliary array to fulfill the purpose, hence this method is an in-place algorithm.

Method 3: using Recursion

Using recursion, we can easily reverse an array in in-place. The idea is to extract the element on each recursive call and reassign it to the array during the traceback process but in the reverse order.

For example, the first element will be assigned at the last of the array, like the following:

Here is the full implementation of the idea in C++:

Output:

3 2 6 5

Although we are not using any extra array but still the method is not efficient in terms of space complexity.

For a large array, the recursion stack and the variable element inside it (holding an array element) can cause space inefficiency.

Comment below, if you know any other method to reverse an array in C++.

Leave a Reply

nine − 3 =