Follow @devglan
Write a Java Program to Reverse an Array in Place Without Using Any Second Array
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
Click to Suggest Your Own 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.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.