Block Swap Algorithm for Array rotation
n=size of elements in array
r=number of rotations
given array is [1,2,3,4,5]
r=2
step 1:
we divide the entire array into two parts
A=r=2;
B=n-r
=>5-2=3
step 2:
[1,2,3,4,5]
Step 3:
Since a s size is<b s size.
Divide B subarray into two different parts.as BI,Br
BI=n-r-r=1
Br=r=2
[1,2,3,4,5]
Step 4:
A=Br
Swap(A,Br)
[4,5,3,1,2]
Again compare the size of non final subarrays,
Step 5:
A s size >B s size.divide subarray into two different parts
AI=r-1
Ar=n-r-r=1
[4,5,3,1,2]
Step 6:
Ai=Bi
Swap(Ai,Bi)
[3,5,4,1,2]
Step 6:
Ai=Bi
Swap(Ai,Bi)
[3,4,5,1,2]
Import java.util.*;
Class codestdio
{
//Swapping r elements
Public static void swap(int arr[],int a,int b,int r)
{
For(int i=0;i<r;i++)
{
Int temp=arr[a+i];
arr[a+i]=arr[b+i];
arr[b+i]=temp;
}
}
//left rotating the array elements
Public static void leftRotate(int arr[],int r)
{
Int n=arr.length;
//if there is no element to rotate=0 or
Equal to size of array
If(r==0//r==n)
return;
int i=r;
int j=n-r;
//perform block swaps till the size of 2 subarrays is equal
While(i!=j)
{
//A’s size is less
If(i<j)
{
Swap(arr,r-I,r+j-I,i);
J=j-I;
//B’s size is less
Else
{
Swap(arr,r-I,r,j);
I=i-j;
}
}
//finally at the end,block swap elements of A and B
Swap(arr,r-I,r,i);
}
//Main function
Public static void main(string[]args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter size of the array”);
Int n=s.nextInt();
Int[]arr=new int[n];
System.out.println(“Enter elements of the array”);
for(int i=0;i<n;i++)
arr[i]=s.nextInt();
System.out.println(“Enter the number of rotations”);
Int no_of_rotations=s.nextInt();
Leftrotate(arr,no_of_rotations);
System.out.println(“Array elements after rotating:”);
System.out.println(arr[i]+” “);
}
}
}