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

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.