Reverse an Array
Understanding Array Reversal
Reversing an array involves changing the order of elements so that the first element becomes the last and vice versa.
We will explore three different methods to reverse an array using Java.
Method 1: Using Iteration
This method iterates through the array swapping elements from both ends.
public class ReverseArray { public static void reverseArray(int[] arr) { int start = 0, end = arr.length - 1, temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; reverseArray(arr); for (int num : arr) { System.out.print(num + " "); } } }
Method 2: Using Recursion
This method reverses the array using a recursive function.
public class ReverseArrayRecursive { public static void reverseArrayRecursive(int[] arr, int start, int end) { if (start >= end) return; int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; reverseArrayRecursive(arr, start + 1, end - 1); } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; reverseArrayRecursive(arr, 0, arr.length - 1); for (int num : arr) { System.out.print(num + " "); } } }
Method 3: Using a Second Array
This method stores the reversed elements in a new array.
public class ReverseArrayNew { public static void reverseArrayNew(int[] arr) { int[] revArr = new int[arr.length]; for (int i = 0; i < arr.length; i++) { revArr[i] = arr[arr.length - i - 1]; } for (int num : revArr) { System.out.print(num + " "); } } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; reverseArrayNew(arr); } }