REVERSE AN ARRAY IN JAVA
Reverse an Array in Java
Introduction
Reversing an array means rearranging its elements such that the first element becomes the last, the second element becomes the second-last, and so on.
This is a common problem that helps in understanding array manipulation and efficient use of loops.
Problem Statement
Given an array:
arr[] = [1, 4, 3, 2, 6, 5]
Output:
[5, 6, 2, 3, 4, 1]Solution Code
import java.util.Arrays;
class GfG {
static void reverseArray(int[] arr) {
int n = arr.length;
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
}
public static void main(String[] args) {
int[] arr = { 1, 4, 3, 2, 6, 5 };
reverseArray(arr);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}Approach Used: In-Place Swapping
Idea
Instead of creating a new array, we reverse the array by swapping elements from both ends.
First element <=> Last element
Second element <=> Second last element
Continue until the middle of the array
How It Works
Find the length of the array
nLoop from
i = 0ton/2Swap:
arr[i]witharr[n - i - 1]
Continue until all elements are reversed
Why This Approach Was Chosen
Does not require extra memory (in-place)
Efficient and simple logic
Reduces unnecessary operations by iterating only half the array
Alternative Approaches
Using an extra array
Create a new array and copy elements in reverse order
Uses extra spaceUsing built-in functions
Available in some languages, but not always preferred in interviews
Why not used here?
The in-place approach is more efficient and better for understanding core logic.
Example
Input:
[4, 5, 1, 2]
Steps:
Swap 4 and 2 = [2, 5, 1, 4]
Swap 5 and 1 = [2, 1, 5, 4]
Output:
[2, 1, 5, 4]Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Conclusion
Reversing an array using the in-place swapping method is an efficient and commonly used approach. It minimizes space usage and provides a clear understanding of array manipulation techniques. This method is preferred in most scenarios due to its simplicity and performance.
Comments
Post a Comment