Java Program to Reverse an Array in place

In this tutorial, we will see how to reverse any given array in java programming language without making use of any separate array.

Now, it would be very easy to reverse an array if we were given the luxury to use another array, the challenge here lies when we are not allowed to use a temporary buffer. This is one of the important interview questions, it is tricky for Java and other languages.

We only need to access array elements and loop over an array using traditional for loop.

Java Program to reverse an array:

import java.util.*;

public class Main{
      
      static void reverse_array(int[] arr) {

        if (arr.length < 2) {
            return;
        }

        for (int i=0; i<arr.length/2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }
    }
    public static void main(String args[]){
       
        int[] arr = {8,9,7,3,5};
        System.out.println("Original: " + Arrays.toString(arr) );
        reverse_array(arr);
        System.out.println("Reversed: " + Arrays.toString(arr) );
    }

 
}

We will loop over the array from start to the middle element and then swap the first element with the last, second element with the second last until we reach the middle element. On reaching the middle element, the array will be sorted without using any additional array.

This algorithm has the time complexity of O(n/2) or O(n) as it needs to iterate over almost half of the elements and perform n/2 swapping. The space complexity of our Java algorithm is O(1) because it doesn’t matter how big the array is, it requires the same amount of space.

It is the fastest way to reverse an array in Java.

Output:

Original: [8, 9, 7, 3, 5]
Reversed: [5, 3, 7, 9, 8]

Also read,

Java Program to Remove all Numbers from a string.

Get the size of a file in java

 

Leave a Reply

Your email address will not be published. Required fields are marked *