VOOZH about

URL: https://www.geeksforgeeks.org/dsa/block-swap-algorithm-for-array-rotation/

⇱ Block swap algorithm for array rotation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Block swap algorithm for array rotation

Last Updated : 23 Jul, 2025

Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. 

👁 Array


Rotation of the above array by 2 will make an array

👁 ArrayRotation1

Algorithm : 

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.


Recursive Implementation:


Output
3 4 5 6 7 1 2 

Time Complexity: O(n)
Auxiliary Space: O(log n)

Iterative Implementation: 
Here is an iterative implementation of the same algorithm. The same utility function swap() is used here.


Output
3 4 5 6 7 1 2 

Time Complexity: O(n)
Auxiliary Space: O(1)

Please see the following posts for other methods of array rotation: 
https://www.geeksforgeeks.org/dsa/array-rotation/ 
https://www.geeksforgeeks.org/dsa/program-for-array-rotation-continued-reversal-algorithm/

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.

Comment
Article Tags:
Article Tags: