- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathArrayRightRotation.java
51 lines (45 loc) · 1.49 KB
/
ArrayRightRotation.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
packagecom.thealgorithms.others;
/**
* Provides a method to perform a right rotation on an array.
* A left rotation operation shifts each element of the array
* by a specified number of positions to the right.
*
* https://en.wikipedia.org/wiki/Right_rotation *
*/
publicfinalclassArrayRightRotation {
privateArrayRightRotation() {
}
/**
* Performs a right rotation on the given array by the specified number of positions.
*
* @param arr the array to be rotated
* @param k the number of positions to rotate the array to the left
* @return a new array containing the elements of the input array rotated to the left
*/
publicstaticint[] rotateRight(int[] arr, intk) {
if (arr == null || arr.length == 0 || k < 0) {
thrownewIllegalArgumentException("Invalid input");
}
intn = arr.length;
k = k % n; // Handle cases where k is larger than the array length
reverseArray(arr, 0, n - 1);
reverseArray(arr, 0, k - 1);
reverseArray(arr, k, n - 1);
returnarr;
}
/**
* Performs reversing of a array
* @param arr the array to be reversed
* @param start starting position
* @param end ending position
*/
privatestaticvoidreverseArray(int[] arr, intstart, intend) {
while (start < end) {
inttemp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}