This post will discuss how to reverse an array in Java.

Practice this problem

1. Naive solution

A simple solution is to create a new array of the same type and size as the input array, fill it with elements from the original array in reverse order, and then copy the contents of the new array into the original one.

Download  Run Code

2. In-place Implementation

The above implementation requires O(n) extra space for the auxiliary array. We can avoid that by modifying the array in-place. That means that the conversion should take place without using an auxiliary array, by overwriting the existing array elements.

An in-place algorithm can be implemented by reading the elements from both ends of the array and swap them, as shown below:

Download  Run Code

 
We can also use recursion for reversing an array without using an auxiliary array. The logic remains the same as the above iterative implementation, but it takes space for the call stack.

Download  Run Code

3. Using Stack (Implicit and Explicit stack)

Another plausible way of reversing an array is to use the stack data structure. The idea is to push each array element 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

 
We can easily convert the above code to use recursion the call stack instead of the explicit stack. Here’s a recursive program that demonstrates it:

Download  Run Code

4. Using Collections.reverse() method

Finally, we can use the reverse() method of the Collections class to reverse the order of the elements in the specified array. Since it accepts a collection as an argument, the idea is to pass a list wrapper backed by the given array.

Download  Run Code

That’s all about reversing an array in Java.