# Rotate an Array in Java

In this blog, we’ll learn how to rotate an array in Java which includes left rotation and right rotation. Along with that, we’ll also learn to rotate an Array in Java by using Juggling Algorithm and By Using Reversing an Array.

## What does it mean to rotate an array in Java?

Rotating an array in Java means shifting its elements in a circular fashion, either to the left or to the right. This can be useful in various scenarios, such as when you want to change the starting point of the array’s elements.

## How to Rotate an Array in Java

Rotating an array in Java involves shifting its elements in a circular manner, either to the left or right. There are several approaches to achieve this rotation, and we’ll describe a few common methods below:

1. Left Rotation
2. Right Rotation
3. By Using Juggling Algorithm
4. By Reversing an Array

### Java Program to Left Rotate the Elements of an Array

```// Rotate an Array in Java
public class ArrayLeftRotationEx {
// function that rotates (left) the array of size n by x
public static void rotateL(int array[], int x, int n) {
for (int i = 0; i < x; i++)
// calling function without passing the number of rotations
rotateArrayByOne(array, n);
}
public static void rotateArrayByOne(int array[], int n) {
int i, temp;
// temporary array to store the newly created array
temp = array[0];
for (i = 0; i < n - 1; i++)
// shifts array element to the left by 1
array[i] = array[i + 1];
array[i] = temp;
}
public static void main(String args[]) {
// array to rotate
int array[] = {1, 20, 56, 16, 10, 6, 77};
// number of rotations to be performed
// we can change the number of rotations accordingly
int r = 1;
// determines the length of array
int n = array.length;
System.out.println("Array before rotation: ");
for (int i = 0; i < n; i++) {
// prints array before rotation
System.out.print(array[i] + " ");
}
System.out.println();
rotateL(array, r, n);
System.out.println("\nArray after left rotation: ");
for (int i = 0; i < n; i++) {
// prints array after performing rotation
System.out.print(array[i] + " ");
}
}
}```

Approach:

The provided code performs a left rotation on an array by shifting its elements to the left by a specified number of positions. It uses a helper function `rotateArrayByOne` to perform a single left rotation, and then another function `rotateL` to rotate the array multiple times based on the given number of rotations.

Code Explanation:

1. `rotateArrayByOne` function:

This function performs a single left rotation on the array. It takes an array and its length `n` as input.

– `temp = array[0];`: This stores the first element of the array in the variable `temp`.

– `for (i = 0; i < n – 1; i++)`: This loop iterates through the array elements except the last one.

– `array[i] = array[i + 1];`: It shifts each element to the left by one position.

– `array[i] = temp;`: Finally, it assigns the value of `temp` to the last element of the array, effectively completing the left rotation.

2. `rotateL` function:

This function performs `x` left rotations on the array using the rotateArrayByOne function. Additionally, it takes an array, the number of rotations `x`, and the length of the array `n` as input.

– `for (int i = 0; i < x; i++)`: This loop iterates `x` times, indicating the number of rotations to perform.

– Inside the loop, we call rotateArrayByOne(array, n) to perform a single left rotation on the array.

3. `main` function:

This is the entry point of the program.

– The array to be rotated is defined: `int array[] = {1, 20, 56, 16, 10, 6, 77};`

– Perform one rotation: `int r = 1;`

– The length of the array: `int n = array.length;`

– The initial array is printed using a loop: `System.out.print(array[i] + ” “);`

– The `rotateL` function is called to perform the left rotations.

– The rotated array is printed after the rotations: `System.out.print(array[i] + ” “);`

#### Output:

``````Array before rotation:
1 20 56 16 10 6 77

Array after left rotation:
20 56 16 10 6 77 1 ``````

Get a Complete list of Online Certification Courses in India here!

In this example, we rotate the array to the left by one position, which results in the first element becoming the last element. Repeat the process for the specified number of rotations (`r = 1` in this case).

### Java Program to Right Rotate the Elements of an Array

```//Rotate an Array in Java
public class ArrayRightRotationEx {
// function that rotates (right) the array of size n by x
public static void rotateR(int array[], int x, int n) {
for (int i = 0; i < x; i++)
// calling function without passing the number of rotations
rotateArrayByOne(array, n);
}
public static void rotateArrayByOne(int array[], int n) {
int i, temp;
// temporary array to store the newly created array
temp = array[n - 1];
for (i = n - 1; i > 0; i--)
// shifts array element to the left by 1
array[i] = array[i - 1];
array[0] = temp;
}
public static void main(String args[]) {
// array to rotate
int array[] = {10, -4, 40, 20, -90, 6, 82, 9, 1, 48};
// number of rotations to be performed
// we can change the number of rotations accordingly
int r = 3;
// determines the length of array
int n = array.length;
System.out.println("Array before rotation: ");
for (int i = 0; i < n; i++) {
// prints array before rotation
System.out.print(array[i] + " ");
}
System.out.println();
rotateR(array, r, n);
System.out.println("\nArray after right rotation: ");
for (int i = 0; i < n; i++) {
// prints array after performing rotation
System.out.print(array[i] + " ");
}
}
}```

Approach:
The goal is to rotate an array to the right by a given number of positions. To achieve this, the code uses a helper function `rotateArrayByOne()` which rotates the array to the right by one position. Then, you call the rotateR() function x times in order to perform the complete rotation.

Explanation of code:
1. The `rotateArrayByOne()` function takes an array and its length `n` as parameters.

2. It saves the last element of the array in a temporary variable `temp`.

3. It then iterates through the array in reverse order (from the last element to the second element).

4. During this iteration, it shifts each element one position to the right by assigning the value of the previous element to the current element.

5. Finally, it assigns the value of `temp` (which was the last element of the original array) to the first element of the array, effectively completing the rotation by one position.

The `rotateR()` function takes the main array, the number of rotations `x`, and the length of the array `n` as parameters. It then repeatedly calls `rotateArrayByOne()` function `x` times to achieve the right rotation.

In the `main()` method:

1. An example array is created.

2. The rotation prints the array before.

3. The `rotateR()` function is called to perform the rotations.

4. After the rotation, the array prints.

Check out our blog on Duplicate Elements in Array in Java here!

#### Output:

``````Array before rotation:
10 -4 40 20 -90 6 82 9 1 48

Array after right rotation:
9 1 48 10 -4 40 20 -90 6 82``````

### By Using Juggling Algorithm

```//Rotate an Array in Java
public class ArrayRotateLEx {
// function that rotates (left) the array of size n by v
void rotateLeft(int array[], int v, int n) {
// execuute if v >= n
v = v % n;
int i, j, k, temp;
// calling gcd() function to determine the GCD of n and d
int gcd = gcd(v, n);
for (i = 0; i < gcd; i++) {
// moves the i-th values of the blocks
temp = array[i];
j = i;
while (true) {
k = j + v;
if (k >= n)
k = k - n;
if (k == i)
break;
array[j] = array[k];
j = k;
}
array[j] = temp;
}
}
// function to print array
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) System.out.print(array[i] + " ");
}
// function to determine the GCD of a nd b
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public static void main(String args[]) {
ArrayRotateLEx arf = new ArrayRotateLEx();
// array to rotate
int array[] = {19, 65, 2, 58, 40, 7, -11, -20, 6};
System.out.println("Array before rotation: ");
arf.printArray(array, 9);
System.out.println("\n");
arf.rotateLeft(array, 2, 9);
System.out.println("Array after left rotation: ");
arf.printArray(array, 9);
}
}```

Approach:

The code uses the Juggling Algorithm to rotate an array to the left by a given number of positions. In addition, this algorithm avoids the need to rotate the array element by element, making it more efficient for larger arrays and a larger number of rotations.

Code Explanation:

1. The `rotateLeft()` method takes three parameters: the array to be rotated, the number of positions to rotate (`v`), and the length of the array (`n`).

2. The code starts by calculating the modulo of `v` with `n` (`v % n`). This step holds importance because if `'v'` is greater than or equal to `'n`‘, it wraps around to make sure that rotations beyond the array’s length are accounted for.

3. The algorithm then calculates the greatest common divisor (GCD) of `v` and `n`. The GCD helps determine the number of cycles required to fully rotate the array.

4. Perform the rotation in cycles. For each cycle, the algorithm moves elements from one block to another. It keeps track of the starting element of the current block (`i`) and a position `j` that indicates where the element from the current block should be moved.

5. Within each cycle, the algorithm uses a loop that updates the position `j` using `j + v`. If `j` exceeds the length of the array, it wraps around by subtracting `n` from `j`.

6. The loop continues until `j` reaches the starting position `i`. This indicates that the current cycle is complete.

7. At the end of each cycle, the algorithm places the temporary value `temp` at the position `j`.

8. The cycles continue until all elements are moved to their correct positions.

9. The method printArray() prints the elements of the array.

10. The `main()` method creates an instance of the `ArrayRotateLEx` class and demonstrates the rotation process using a sample array.

#### Output:

``````Array before rotation:
19 65 2 58 40 7 -11 -20 6

Array after left rotation:
2 58 40 7 -11 -20 6 19 65 ``````

Also, learn about  Java Program to Find the Largest Number in an Array, Now!

### By Reversing an Array

```//Rotate an Array in Java
import java.util.Arrays;
public class RotateArrayRightEx {
// function to swap array elements
public static void swapElement(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// function to reverse a given subarray
public static void reverseArr(int[] array, int low, int high) {
for (int i = low, j = high; i < j; i++, j--) {
swapElement(array, i, j);
}
}
// function to rotate array to the right by k positions
public static void rotateRight(int[] array, int k, int n) {
// reverse the last k elements
reverseArr(array, n - k, n - 1);
// reverse the first n-k elements
reverseArr(array, 0, n - k - 1);
// reverse the complete array
reverseArr(array, 0, n - 1);
}
public static void main(String args[]) {
// array to rotate
int[] array = {11, 78, 8, 91, 57, 22, 59};
// k denotes the position to shift
int k = 3;
System.out.println("Array before rotation: ");
System.out.println(Arrays.toString(array));
System.out.println();
System.out.println("Array after right rotation: ");
rotateRight(array, k, array.length);
System.out.println(Arrays.toString(array));
}
}```

Approach:

The approach used in this code involves a three-step process for rotating the array to the right by `k` positions:

1. Reverse the array’s last ‘k’ elements.

2. Reverse the first `n – k` elements of the array (where `n` is the length of the array).

3. Reverse the entire array.

By following these three steps, the array effectively gets rotated to the right by `k` positions.

Code Explanation:

In the `main()` method:

1. Someone creates an example array.

2. The array is printed before the rotation.

3. The rotateRight`()` function performs the right rotation by `k` positions when called.

4. The array is printed after the rotation.

The `swapElement()` function swaps two elements in an array. The `reverseArr()` function reverses a given subarray within the array. The `rotateRight()` function orchestrates the three-step rotation process: reversing the necessary subarrays.

By utilizing the reverse subarray technique, this code achieves the right rotation in a more efficient manner compared to the initial code example you provided.

#### Output:

``````Array before rotation:
[11, 78, 8, 91, 57, 22, 59]

Array after right rotation:
[57, 22, 59, 11, 78, 8, 91]``````

In conclusion, rotating an array in Java involves shifting its elements circularly, either to the left or right. Left rotation changes the starting point of elements by moving them to the left, while right rotation shifts elements to the right. Different approaches can execute these operations.

We believe our discussion on ‘How to Rotate an Array in Java’ has provided valuable insights. Keep checking for more updates and programming blogs by visiting our Newtum website. Visit our website to learn more about our programs, including PHP, C Programming for kids, and Happy Coding!