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

1. Using Auxiliary Array

A simple solution is to create an auxiliary array of the same type and size as the input array, fill it with elements from the input array backward, and then copy the auxiliary array’s contents into the original one. The time complexity of this solution is O(n) and requires O(n) extra space, where n is the size of the input.

Download  Run Code

2. In-place Implementation

The above implementation requires O(n) extra space for the auxiliary array. A linear in-place algorithm can be implemented by reading the elements from both ends of the array and swap them, as demonstrated below:

Download  Run Code

3. Using Recursion

We can easily convert the above code to use the recursion. The logic remains the same as the above iterative implementation but requires O(n) implicit space for the call stack.

Download  Run Code

 
Here’s another recursive program that stores elements into the call stack and then put them back into the array in the correct order when the recursion unfolds.

Download  Run Code