How I can reverse a Java Array?



To reverse an array, swap the first element with the last element and the second element with second last element and so on if the array is of odd length leave the middle element as it is.

In short swap the 1st element with the 1st element from last, second element with the second element from last i.e. ith element with the ith element from the last you need to do this till you reach the midpoint of the array.

 If i is the first element of the array (length of the array –i-1) will be the last element, therefore, swap array[i] with array[(length of the array –i-1)] from the start to the midpoint of the array:

Example

public class ReversingAnArray {
   
   public static void main(String[] args) {
      int[] myArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
      int size = myArray.length;

      for (int i = 0; i < size / 2; i++) {
         int temp = myArray[i];
         myArray[i] = myArray[size - 1 - i];
         myArray[size - 1 - i] = temp;
      }
      System.out.println("Array after reverse:: ");
      System.out.println(Arrays.toString(myArray));
   }
}

Output

Array after reverse::
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician


Advertisements