To reverse an array in Java with an optimized approach, you can use a two-pointer technique. Here's an example implementation:
javapublic class ReverseArray {
public static void reverse(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
// Swap elements at left and right indices
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
// Move the pointers towards the center
left++;
right--;
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Original Array: " + Arrays.toString(arr));
reverse(arr);
System.out.println("Reversed Array: " + Arrays.toString(arr));
}
}
In this example, the reverse
method takes an array of integers (arr
) as input. It initializes two pointers, left
and right
, pointing to the first and last elements of the array, respectively. It then iterates through the array, swapping the elements at the left
and right
indices using a temporary variable. After each swap, the left
pointer is incremented and the right
pointer is decremented, moving towards the center of the array. This process continues until the left
pointer crosses the right
pointer, resulting in a reversed array.
The example demonstrates the reversal of the array {1, 2, 3, 4, 5}
. The output will be:
javascriptOriginal Array: [1, 2, 3, 4, 5]
Reversed Array: [5, 4, 3, 2, 1]
Using the two-pointer technique ensures that each element in the array is swapped only once, resulting in an optimized approach for reversing the array.