February 7, 2022

Reverse an Array In-place Java Program

In this post we’ll see how to reverse an array in-place Java. Though it is easy to take another array and start storing elements from the last index to the first index of the original array to this new array in order to get reversed array but this approach means using auxiliary data structure, a new array to store the reversed elements making the space complexity of this approach O(n).

Using an in-place algorithm means additional space is not used and the space provided by the input data structure itself is used to modify the elements to get the output. Thus the Java program to reverse an array in-place will not use any additional array and swap elements with in the original array to get the reversed array as output.

Reverse array in-place Java program

One thing to note here is that you don’t need to iterate the whole array, you need to iterate only n/2 array for the array of size n. Since the first and last elements, second and second last and so on are swapped in each iteration so by the time middle element is reached the array is already reversed.

reverse array in place java
import java.util.Arrays;

public class ArrayReverseInplace {
  public static void main(String[] args) {
    int[] arr = {61, 34, 10, 0, 15, 112, 53, 78, 39, 68};

  static void reverseArray(int[] arr) {
    int n = arr.length;
    int temp;
    // Iterate till array length/2
    for (int i = 0; i < n / 2; i++) { 
      temp = arr[i]; 
      // Swapping
      arr[i] = arr[n - i - 1]; 
      arr[n - i - 1] = temp; 
    System.out.println("Reversed Array- " + Arrays.toString(arr));
Reversed Array- [68, 39, 78, 53, 112, 15, 0, 10, 34, 61]

As you can see in the Java program for reversing array in-place same input array space is used to do the reversal, only extra space required is for the auxiliary variables used.

That's all for the topic Reverse an Array In-place Java Program. If something is missing or you have something to share about the topic please write a comment.

You may also like

No comments:

Post a Comment