Reverse an array in Java

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


 

1. Naive

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

 

Download   Run Code

 

2. In-place implementation

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 elements of the array.

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 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 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

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

 

Download   Run Code

 

4. Collections#reverse method

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

 

Download   Run Code

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of