Block Swap Algorithm For Array Rotation
Block Swap Algorithm For Array Rotation
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]+” “);
}
}
}