Java Program to Reverse an Array
In this Java program, we will learn how to reverse an array in Java.
Java Program to Reverse an Array
We will reverse the array by swapping the elements of the array. We will use two pointers, one pointing to the start of the array and the other pointing to the end of the array. We will swap the elements of the array pointed by the two pointers and move the pointers towards each other until they meet in the middle of the array.
Here is the Java program to reverse an array:public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int start = 0;
int end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
System.out.println("Reversed Array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:
Space Complexity: O(1) - We are not using any extra space to reverse the array that's why the space complexity is O(1).
Reversed Array: 5 4 3 2 1Time Complexity: O(n) - We are iterating through the array once to reverse it that's why the time complexity is O(n).
Space Complexity: O(1) - We are not using any extra space to reverse the array that's why the space complexity is O(1).
- Recommended Links
- Selenium Interview Questions