题目:有n个整数,使前面各数顺序向后移m个位置,最后m个数变成前面m个数,
如:
1 2 3 4 5 6 7 8 9
n=9,m=3时
移动后是:
7 8 9 1 2 3 4 5 6
编写一个程序完成以上过程。
思路:每当移动一个数,如当移动一次,将最后一个数移动到最前面,倒数第二个数变成最后一个数,依次类推,直到所有的数移动完毕。
移动所有数的过程和移动一个数的过程一样,所以可以用递归解决。
#include<stdio.h>
void input(int *a,int n)
{
int i;
for(i=0;i<n;i++)
{
scanf("%d",a++);
}
}
void ouput(int *a,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d ",*a++);
}
}
void move(int a[],int n,int m)
{
int *p,a_end;
a_end=*(a+n-1);
for(p=a+n-1;p>a;p--)
{
*p=*(p-1);
}
*a=a_end;
m--;
if(m>0) move(a,n,m);
}
int main()
{
int n,m;
int a[100];
scanf("%d%d",&n,&m);
input(a,n);
//sort(a,n,m);
move(a,n,m);
ouput(a,n);
return 0;
}