Java Program to Reverse an Array Without Using Another Array

In this post, we will write a Java program to reverse an Array without using another Array.
This is trick question has asked me many times in the interview ( for beginners and experienced ).
Logic is very simple, follow the steps:
  1. Find the middle element using formula
final int middle = array.length / 2;
  1. Iterate over an array and swap the elements using a temp variable.
/**
 * 
 * @author RAMESH
 *
 */
public class ReverseArrayWithoutAnotherArray {

 public static void main(final String[] args) {

  final int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

  final int middle = array.length / 2;

  int temp;
  int j = array.length -1;
  
  for(final int a : array){
   System.out.println(" before reverse :: " + a);
  }
  for (int i = 0 ; i < middle; i++, j--) {
   temp = array[i];
   array[i] = array[j];
   array[j] = temp;
  }
  
  for(final int a : array){
   System.out.println(" after reverse :: " + a);
  }
 }
}
Output:
 before reverse :: 1
 before reverse :: 2
 before reverse :: 3
 before reverse :: 4
 before reverse :: 5
 before reverse :: 6
 before reverse :: 7
 before reverse :: 8
 before reverse :: 9
 before reverse :: 10
 after reverse :: 10
 after reverse :: 9
 after reverse :: 8
 after reverse :: 7
 after reverse :: 6
 after reverse :: 5
 after reverse :: 4
 after reverse :: 3
 after reverse :: 2
 after reverse :: 1

Comments