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.
- Quickly find multiple left rotations of an array | Set 1
- Maximum sum of i*arr[i] among all rotations of a given array
- Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
- Program to cyclically rotate an array by one
- Rearrange positive and negative numbers in O(n) time and O(1) extra space
- Check for Majority Element in a sorted array
- Sort elements by frequency | Set 1
- Leaders in an array
- Maximum sum such that no two elements are adjacent
- Reversal algorithm for array rotation
- Program for array rotation
- Write a program to reverse an array or string
- Merge an array of size n into another array of size m+n
- Search an element in a sorted and rotated array
- Majority Element
Improved By : AbhijeetPal