1. Introduction
Rotating an array means moving its elements to the right or to the left by a certain number of positions. In this blog post, we will see how to rotate an array to the right by a given number of positions in Java.
2. Program Steps
1. Initialize the array and the number of positions n by which the array has to be rotated.
2. Compute the length of the array.
3. Create a temporary array of size n to store the elements that will be shifted.
4. Copy the last n elements from the original array to the temporary array.
5. Shift the remaining elements in the original array to the right by n positions.
6. Copy the elements from the temporary array back to the original array at the beginning.
3. Code Program
public class RotateArray {
public static void main(String[] args) {
// Step 1: Initialize the array and the number of positions n by which the array has to be rotated
int[] array = {1, 2, 3, 4, 5, 6, 7};
int n = 3;
// Step 2: Compute the length of the array
int length = array.length;
// Step 3: Create a temporary array of size n to store the elements that will be shifted
int[] temp = new int[n];
// Step 4: Copy the last n elements from the original array to the temporary array
System.arraycopy(array, length - n, temp, 0, n);
// Step 5: Shift the remaining elements in the original array to the right by n positions
System.arraycopy(array, 0, array, n, length - n);
// Step 6: Copy the elements from the temporary array back to the original array at the beginning
System.arraycopy(temp, 0, array, 0, n);
// Printing the rotated array
for (int i : array) {
System.out.print(i + " ");
}
}
}
Output:
5 6 7 1 2 3 4
4. Step By Step Explanation
In Step 1, we initialize the array and the number of positions n by which the array has to be rotated.
During Step 2, we compute the length of the array for later use in copying and shifting elements.
In Step 3, a temporary array of size n is created to store the elements that will be shifted.
For Step 4, we copy the last n elements from the original array to the temporary array using System.arraycopy().
In Step 5, we shift the remaining elements in the original array to the right by n positions.
Finally, in Step 6, we copy the elements from the temporary array back to the original array at the beginning, completing the rotation. After the rotation, we print out the modified array.