Recently I learnt about the array rotation in linear time using Juggling algorithm. Here is the snippet regarding the left rotation of the array.
void ArrayRotate (int A[], int n, int k)
{
int d=-1,i,temp,j;
for(i=0;i<gcd(n,k);i++)
{
j=i;
temp=A[i];
while(1)
{
d=(j+k)%n;
if(d==i)
break;
A[j]=A[d];
j=d;
}
A[j]=temp;
}
}
but now I am stuck as how to use this Juggling algorithm to rotate the array in the Right Direction.
1,2,3,4,5 (given array)
5,1,2,3,4 (after 1 right rotation)
(I had solved this question using the brute force method and reversal method.)
for(i=n-1;i<gcd(n,k);i--)-- Off topic, but you are computinggcd(n,k)on each iteration of your loop. Simply calculate it once, store it in a variable, and use that variable in theforloop.for(i=n-1;i<gcd(n,k);i--)is going to stop immediately, unlessn < kandnis a prime factor ofk, surely ?