Skip to content

Reverse an Array

In-place two-pointer technique to reverse an array.

package DSA.Arrays;
import java.util.Scanner;
public class reverseArray {
public static int[] reverse(int arr[]) {
int first = 0, last = arr.length - 1;
while (first <= last) {
int temp = arr[first];
arr[first] = arr[last];
arr[last] = temp;
first++;
last--;
}
return arr;
}
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter The Length of the array: ");
int length = sc.nextInt();
System.out.println("Enter the array values: ");
int numbers[] = new int[length];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = sc.nextInt();
}
numbers = reverse(numbers);
System.out.println("The reverse arrey is : ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
} catch (Exception e) {
System.out.println(e);
}
}
}