Skip to content

Feature/4638 array right rotation #5014

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/test/java/com/thealgorithms/others/ArrayRightRotation.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.thealgorithms.others;

public class ArrayRightRotation {
public static int[] rotateRight(int[] arr, int k) {
if (arr == null || arr.length == 0 || k < 0) {
throw new IllegalArgumentException("Invalid input");
}

int n = 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);

return arr;
}

private static void reverseArray(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.thealgorithms.others;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import org.junit.jupiter.api.Test;

class ArrayRightRotationTest {

@Test
void testArrayRightRotation() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
int[] expected = {5, 6, 7, 1, 2, 3, 4};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}

@Test
void testArrayRightRotationWithZeroSteps() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 0;
int[] expected = {1, 2, 3, 4, 5, 6, 7};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}

@Test
void testArrayRightRotationWithEqualSizeSteps() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = arr.length;
int[] expected = {1, 2, 3, 4, 5, 6, 7};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}

@Test
void testArrayRightRotationWithLowerSizeSteps() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 2;
int[] expected = {6, 7, 1, 2, 3, 4, 5};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}

@Test
void testArrayRightRotationWithHigherSizeSteps() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 10;
int[] expected = {5, 6, 7, 1, 2, 3, 4};
int[] result = ArrayRightRotation.rotateRight(arr, k);
assertArrayEquals(expected, result);
}
}