Write a Java program to reverse an array.
This program reverses an array in-place and prints both the original and the reversed arrays. Here’s how it works:
class Main {
public static void main(String[] args) {
int[] arr = {1, 5, 2, 5, 7};
// Print the original array
System.out.print("Original array: ");
printArr(arr);
// Reverse the array
revArr(arr);
// Print the reversed array
System.out.print("Reversed array: ");
printArr(arr);
}
// Method to print the array
public static void printArr(int[] arr) {
for (int num : arr) {
System.out.print(num + " "); // Add space between numbers
}
System.out.println();
}
// Method to reverse the array
public static void revArr(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
Original array: 1 5 2 5 7
Reversed array: 7 5 2 5 1
Key Features
Reversing Logic:
The revArr method uses two pointers: start and end.
The pointers begin at opposite ends of the array and move towards the center, swapping elements as they go.
Printing the Array:
The printArr method iterates over the array using an enhanced for loop and prints its elements with spaces in between.
Efficiency:
The reversal algorithm runs in O(n) time since each element is accessed only once.
The space complexity is O(1) because the reversal is performed in-place without extra storage.
Why This Method?
In-place operation: Avoids creating a new array, saving memory.
Two-pointer technique: Simple and effective for array reversal.