Array Rotation simply means shifting the array elements to the left or right of the array by specified positions. An array can be rotated to the left(clockwise) or to the right (anti-clockwise) to the given number of positions. Now let us look at a program for left rotation of an array and right rotation of an array.
Left Rotation of Array
Left rotation of an array means shifting of the elements in an array towards the left as shown in the below image. Left rotation means rotating the elements of the array in a clockwise direction to the specified number of positions.
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
public class Main { /*Function to left rotate arr[] of size n by d*/ public static void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); // Function is called for no_of_rotation times } public static void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; // Left shift by one arr[i] = temp; } // Driver program to test above functions public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int no_of_rotations = 1; int n = arr.length; System.out.println("Array Elements before rotating : "); for(int i = 0 ; i < n ; i++) { System.out.print(arr[i]+ " "); // Printing elements before rotation } leftRotate(arr, no_of_rotations, n); System.out.println("\nArray Elements after rotating : "); for(int i = 0 ; i < n ; i++) { System.out.print(arr[i] + " "); // Printing elements after rotation } } } |
Output: