Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
#include<stdio.h>
void reverse(int *nums,int start,int end)
{
int t;
while(start<end)
{
t=*(nums+end-1);
*(nums+end-1)=*(nums+start);
*(nums+start)=t;
start++;
end--;
}
}
void rotate(int *nums,int numsSize,int k)
{
k=k%(numsSize);
reverse(nums,0,numsSize-k);
reverse(nums,numsSize-k,numsSize);
reverse(nums,0,numsSize);
}
int main(void)
{
int a[]={1,2,3,4,5,6,7};
int i;
rotate(a,7,3);
for(i=0;i<7;i++)
{
printf("%d\n",a[i]);
}
}