Write a function rotate(ar, d, n) that rotates arr of size n by d elements.
Rotation of the above array by 2 will make array
Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change ABlBr into BrBlA. Now A is at its final place, so recur on pieces of B. b) If A is longer, divide A into Al and Ar such that Al is of same length as B Swap Al and B to change AlArB into BArAl. Now B is at its final place, so recur on pieces of A. 2) Finally when A and B are of equal size, block swap them.
Here is iterative implementation of the same algorithm. Same utility function swap() is used here.
Time Complexity: O(n)
Please see following posts for other methods of array rotation:
Please write comments if you find any bug in the above programs/algorithms or want to share any additional information about the block swap algorithm.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Reversal algorithm for right rotation of an array
- Reversal algorithm for array rotation
- C Program for Reversal algorithm for array rotation
- Java Program for Reversal algorithm for array rotation
- Program for array rotation
- Left rotation of an array using vectors in C++
- Circular rotation of an array using deque in C++
- Left Rotation and Right Rotation of a String
- Find the Rotation Count in Rotated Sorted array
- Print left rotation of array in O(n) time and O(1) space
- Check if array can be sorted with one swap
- Maximize distance between smallest and largest Array elements by a single swap
- Lexicographically smallest array formed by at most one swap for every pair of adjacent indices
- Find starting index for every occurrence of given array B in array A using Z-Algorithm
- Median of an unsorted array using Quick Select Algorithm
- Queries for Count of divisors of product of an Array in given range | Set 2 (MO's Algorithm)
- Sorting possible using size 3 subarray rotation
- Clockwise rotation of Linked List
- Lexicographically minimum string rotation | Set 1
- Rotate Linked List block wise