Java Program to Reverse Array with Output and Explanation
for (int i = 0; i < arr.length / 2; i++) { int temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; }.Examples
How to Think About It
Algorithm
Code
public class ReverseArray { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; for (int i = 0; i < arr.length / 2; i++) { int temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } for (int num : arr) { System.out.print(num + " "); } } }
Dry Run
Let's trace the array [1, 2, 3, 4, 5] through the code.
Initial array
arr = [1, 2, 3, 4, 5]
First iteration (i=0)
Swap arr[0] and arr[4]: arr = [5, 2, 3, 4, 1]
Second iteration (i=1)
Swap arr[1] and arr[3]: arr = [5, 4, 3, 2, 1]
Loop ends
i=2 is not less than arr.length/2 (2), stop.
| i | arr after swap |
|---|---|
| 0 | [5, 2, 3, 4, 1] |
| 1 | [5, 4, 3, 2, 1] |
Why This Works
Step 1: Swapping elements
We swap the element at the current index with the element at the corresponding position from the end using a temporary variable temp.
Step 2: Loop until middle
The loop runs only until the middle of the array because after that, elements would be swapped back to original positions.
Step 3: In-place reversal
This method reverses the array in place without using extra memory, making it efficient.
Alternative Approaches
public class ReverseArray { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int[] reversed = new int[arr.length]; for (int i = 0; i < arr.length; i++) { reversed[i] = arr[arr.length - 1 - i]; } for (int num : reversed) { System.out.print(num + " "); } } }
import java.util.Arrays; import java.util.Collections; public class ReverseArray { public static void main(String[] args) { Integer[] arr = {1, 2, 3, 4, 5}; Collections.reverse(Arrays.asList(arr)); for (int num : arr) { System.out.print(num + " "); } } }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs half the length of the array, so time complexity is O(n) where n is the array size.
Space Complexity
The reversal is done in place using a temporary variable, so space complexity is O(1).
Which Approach is Fastest?
In-place swapping is fastest and uses least memory compared to creating a new array or using Collections.reverse.
| Approach | Time | Space | Best For |
|---|---|---|---|
| In-place swap | O(n) | O(1) | Memory efficient, fast |
| New array | O(n) | O(n) | Preserving original array |
| Collections.reverse | O(n) | O(n) | Using built-in methods with objects |