Skip to content

Commit 7d13cac

Browse files
committed
feat: Add utility class to reverse an array in place with print support
🧠 Logic: - `reverseArray()` performs in-place reversal using two pointers (`left`, `right`) and swaps elements until they meet. - `printArray()` displays the array contents with a prefix message for clarity. - Main method demonstrates functionality by reversing a sample array `{1, 2, 8, 4, 5}`. - Includes input validation for null arrays. Signed-off-by: Somesh diwan <[email protected]>
1 parent add390a commit 7d13cac

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Utility class for array reversal operations.
3+
*/
4+
public class ArrayReverser {
5+
private static final String PRINT_SEPARATOR = " ";
6+
7+
/**
8+
* Reverses the elements of an array in place.
9+
*
10+
* @param arr the array to be reversed
11+
* @throws IllegalArgumentException if the input array is null
12+
*/
13+
public static void reverseArray(int[] arr) {
14+
if (arr == null) {
15+
throw new IllegalArgumentException("Input array cannot be null");
16+
}
17+
18+
int left = 0;
19+
int right = arr.length - 1;
20+
21+
while (left < right) {
22+
int temp = arr[left];
23+
arr[left] = arr[right];
24+
arr[right] = temp;
25+
left++;
26+
right--;
27+
}
28+
}
29+
30+
/**
31+
* Prints the array elements with a space separator.
32+
*
33+
* @param arr the array to print
34+
* @param prefix the prefix message to print before the array
35+
*/
36+
private static void printArray(int[] arr, String prefix) {
37+
System.out.println(prefix);
38+
for (int num : arr) {
39+
System.out.print(num + PRINT_SEPARATOR);
40+
}
41+
System.out.println();
42+
}
43+
44+
public static void main(String[] args) {
45+
int[] arr = {1, 2, 8, 4, 5};
46+
printArray(arr, "Original Array:");
47+
reverseArray(arr);
48+
printArray(arr, "Reversed Array:");
49+
}
50+
}

0 commit comments

Comments
 (0)