Skip to content

Commit 8804cec

Browse files
Feature/4638 array right rotation (TheAlgorithms#5014)
* Create ArrayRightRotationTest.java * Create ArrayRightRotation.java * The updated one * The updated one * Added the test cases * Added new test cases! * Update ArrayRightRotation.java * Update ArrayRightRotationTest.java
1 parent 19b7a22 commit 8804cec

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.thealgorithms.others;
2+
3+
public class ArrayRightRotation {
4+
public static int[] rotateRight(int[] arr, int k) {
5+
if (arr == null || arr.length == 0 || k < 0) {
6+
throw new IllegalArgumentException("Invalid input");
7+
}
8+
9+
int n = arr.length;
10+
k = k % n; // Handle cases where k is larger than the array length
11+
12+
reverseArray(arr, 0, n - 1);
13+
reverseArray(arr, 0, k - 1);
14+
reverseArray(arr, k, n - 1);
15+
16+
return arr;
17+
}
18+
19+
private static void reverseArray(int[] arr, int start, int end) {
20+
while (start < end) {
21+
int temp = arr[start];
22+
arr[start] = arr[end];
23+
arr[end] = temp;
24+
start++;
25+
end--;
26+
}
27+
}
28+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.thealgorithms.others;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class ArrayRightRotationTest {
8+
9+
@Test
10+
void testArrayRightRotation() {
11+
int[] arr = {1, 2, 3, 4, 5, 6, 7};
12+
int k = 3;
13+
int[] expected = {5, 6, 7, 1, 2, 3, 4};
14+
int[] result = ArrayRightRotation.rotateRight(arr, k);
15+
assertArrayEquals(expected, result);
16+
}
17+
18+
@Test
19+
void testArrayRightRotationWithZeroSteps() {
20+
int[] arr = {1, 2, 3, 4, 5, 6, 7};
21+
int k = 0;
22+
int[] expected = {1, 2, 3, 4, 5, 6, 7};
23+
int[] result = ArrayRightRotation.rotateRight(arr, k);
24+
assertArrayEquals(expected, result);
25+
}
26+
27+
@Test
28+
void testArrayRightRotationWithEqualSizeSteps() {
29+
int[] arr = {1, 2, 3, 4, 5, 6, 7};
30+
int k = arr.length;
31+
int[] expected = {1, 2, 3, 4, 5, 6, 7};
32+
int[] result = ArrayRightRotation.rotateRight(arr, k);
33+
assertArrayEquals(expected, result);
34+
}
35+
36+
@Test
37+
void testArrayRightRotationWithLowerSizeSteps() {
38+
int[] arr = {1, 2, 3, 4, 5, 6, 7};
39+
int k = 2;
40+
int[] expected = {6, 7, 1, 2, 3, 4, 5};
41+
int[] result = ArrayRightRotation.rotateRight(arr, k);
42+
assertArrayEquals(expected, result);
43+
}
44+
45+
@Test
46+
void testArrayRightRotationWithHigherSizeSteps() {
47+
int[] arr = {1, 2, 3, 4, 5, 6, 7};
48+
int k = 10;
49+
int[] expected = {5, 6, 7, 1, 2, 3, 4};
50+
int[] result = ArrayRightRotation.rotateRight(arr, k);
51+
assertArrayEquals(expected, result);
52+
}
53+
}

0 commit comments

Comments
 (0)