Array Rotation in Java
In this section, we will learn what is rotation of an array and how to rotate an array in through a Java program.
Java Array Rotation
The rotation of an array simply means to shift the array elements of an array to the specified positions. We can rotate an array in both directions i.e. clockwise and anti-clockwise. We can perform any number of rotations on an array.
Types of Rotation
- Left Rotation
- Right Rotation
Left Rotation
In left rotation, the array elements rotated to the left with the specified number of positions. It rotates the array in the clockwise direction. The lowest index element moves to the highest index in rotation.
Example
Suppose, [1, 2, 3, 4, 5] is an array and we need to perform 2 left rotations on an array then the array become:
Given array = [1, 2, 3, 4, 5]
Array after first left rotation = [2, 3, 4, 5, 1]
Array after second left rotation = [3, 4, 5, 1, 2]
ArrayLeftRotation.java
Output:
Right Rotation
In the right rotation, the array elements rotated to the right with the specified number of positions. It rotates the array in an anti-clockwise direction.
Example:
Suppose [4, 7, 9, 0, 1] is an array and we need to perform 2 left rotations on an array then the array become:
Given array = [4, 7, 9, 0, 1]
Array after first left rotation = [1, 4, 7, 9, 0]
Array after second left rotation = [0, 1, 4, 7, 9]
ArrayRightRotation.java
Output:
How to rotate an array?
There are the following four ways to rotate an array:
- Using Temp Array
- Rotate Element One by One
- By Using Juggling Algorithm
- By Reversing an Array
Using Temp Array
Input array[] = [11, 22, 33, 44, 55], Number of rotations (r) = 2, Number of elements (n) = 5
1. Store the first r elements in a temp array.
2. Move rest array to the left.
3. After that, append the element of the temparray[] to the array[].
Rotate Element One by One
By Using Juggling Algorithm
Juggling algorithm is the advanced version of the second (rotate element one by one) approach. The algorithm divides the whole array into different sets. We can find the number of sets by finding the GCD of r and n. After getting the sets, move the elements within the sets. Let’s understand the algorithm through an example.
Suppose, a[] is an array having 12 (n) elements (1, 2, 3,……, 12) and we need to perform 3 (d) rotations, then according to the algorithm:
GCD of n and d = 3
Elements are first moved in the first set. After the movement, we get the following array:
{4, 2, 3, 7, 5, 6, 10, 8, 9, 1, 11, 12}
Movement of elements in second set.
{4, 5, 3, 7, 8, 6, 10, 11, 9, 1, 2, 12}
At last, movement of elements in third set.
{4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3}
Let’s implement the above approach in a Java program.
JugglingAlgo.java
Output:
By Reversing an Array
The idea is to reverse the last k elements of the input array and then reverse the remaining n-k elements. Using the mechanism, we get the right rotated array by reversing the complete array.
RotateReverse.java
Output: