Block swap algorithm for array rotation in Java

In this tutorial, we’ll learn the block swap algorithm for array rotation (left) in Java.
Consider a given array (a) :

1,  2,  3,  4,  5,  6,  7,  8,  9

After rotating the array by d=4, we get,

5,  6,  7,  8,  9,  1,  2,  3,  4


The approach to solving the problem is as follows :

  • Create 2 arrays A and B where A is from 0 to d-1 and B is from d to n-1 (last index of the array).
  • Now compare both arrays A and B.
  • If the size of A is smaller than B then divide array B into 2 parts B1 and B2 such that the size of B2 is equal to the size of A. Then perform swap operation on A and B2. Hence, the array becomes B2B1A. Thus, the position of the array A is now fixed.
  • If the size of B is smaller than A then divide array A into 2 parts A1 and A2 such that the size of A1 is equal to the size of B. Then perform swap operation on A1 and B. Hence, the array becomes BA2A1. Thus, the position of the array B is now fixed.
  • Keep on performing the above steps until the size of A equals the size of B.
  • After each step, a smaller array is fixed in its proper position and by repeating the above steps we get the desired array.
  • Now, when the size of A equal B, perform the last swap operation on both of them.

Implementation :

The code for the above approach is as follows :

import java.util.*;
import java.lang.*;
class CodeSpeedy 
    public static void Rotation(int a[],int d,int n)  
        int i=d;  
        int j=n-d;  
            int x=d-i;
                int y=d+j-i;
    public static void swapping(int a[],int x,int y,int d)  
        for(int i=0;i<d;i++)  
            int temp=a[x+i];  
    public static void main (String[] args)  
        int a[]={1,2,3,4,5,6,7,8,9};  
        for(int i=0;i<9;i++)  
            System.out.print(a[i]+" ");  


Output :
5 6 7 8 9 1 2 3 4


Recommended Posts:

Block swap algorithm for rotation of the array

How to swap both diagonals of a matrix in C++

Leave a Reply

Your email address will not be published. Required fields are marked *