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.
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 41 42 43 44 45 46 47 48 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace csharp_console_examples { internal class Program { 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; } static void Main(string[] args) { int[] arr = { 1, 2, 3, 4, 5, 6, 7 }; int no_of_rotations = 1; int n = arr.Length; Console.WriteLine("Array Elements before rotating : "); for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); // Printing elements before rotation } leftRotate(arr, no_of_rotations, n); Console.WriteLine("\nArray Elements after rotating : "); for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); // Printing elements after rotation } Console.ReadLine(); } } } |
Output: