Array rotation is the process of shifting elements of the array in a specific direction and rotate the last element to first or first to last based on the direction of rotation of the array.
There are two types of array rotation:
- Lift Shift: Leftward shifting of elements from index n to n-1, and shift element at the first index to the last index.
- Right Shift: Rightward shifting of elements from index n-1 to n, and shift element at last index to the first index.
Example:
Array: {2, 5, 7, 9, 1, 3}
Left shifted array: {5, 7, 9, 1, 3, 2}
Right shifted array: {3, 2, 5, 7, 9, 1}
Now, to left rotate array by n elements, we will first store the last element of the array in a temporary variable. And run a loop from last to first. And copy element at the n-1 position to n and so on.
Program:
Output
Explanation:
In this above code, we have a function that is used to right rotate an array by k steps. The function calls another function which does the rotation work. The function calls a function to rotate the array single step k times.
need an explanation for this answer? contact us directly to get an explanation for this answer