forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseArrays.java
More file actions
38 lines (28 loc) · 997 Bytes
/
Copy pathReverseArrays.java
File metadata and controls
38 lines (28 loc) · 997 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package modern.challenge;
public final class ReverseArrays {
private ReverseArrays() {
throw new AssertionError("Cannot be instantiated");
}
public static void reverse(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Array cannot be null");
}
for (int leftHead = 0, rightHead = arr.length - 1;
leftHead < rightHead; leftHead++, rightHead--) {
int elem = arr[leftHead];
arr[leftHead] = arr[rightHead];
arr[rightHead] = elem;
}
}
public static <T> void reverse(T[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Array cannot be null");
}
for (int leftHead = 0, rightHead = arr.length - 1;
leftHead < rightHead; leftHead++, rightHead--) {
T elem = arr[leftHead];
arr[leftHead] = arr[rightHead];
arr[rightHead] = elem;
}
}
}