Write a Java Program to Reverse an Array in Place Without Using Any Second Array

Write a Java Program to Reverse an Array in Place Without Using Any Second Array thumbnail
37K
By Dhiraj Ray 10 March, 2018

Program Description

Write a java program to reverse an array in place without using any second array.Here, we can loop till the middle index of the array and swap the first element with last element, swap second element with second last element until we reach the middle of the array.

package com.devglan.set2;

import java.util.Arrays;

public class ArrayReverse {

    public int[] reverse(int [] array){

        if(array == null || array.length <= 1){
            System.out.println("Invalid array.");
        }
        for (int i = 0; i < array.length / 2; i++) {
            int temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    public static void main(String[] args){
        ArrayReverse arrayReverse = new ArrayReverse();
        int[] input = {1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println("Original array" + Arrays.toString(input));
        System.out.println("Reversed array" + Arrays.toString(arrayReverse.reverse(input)));
    }
}

Explanation

Loop till the middle index of the array and swap the first element with last element, swap second element with second last element until you reach the middle of the array.

Share

❤️ Liked this article?

If it saved you time, consider buying me a coffee to support future improvements.

About The Author

author-image
I write about cryptography, web security, and secure software development. Creator of practical crypto validation tools at Devglan.