实例四十六:数组元素平移
问题描述:
将一维数组中的所有元素循环向右平移若干位(要求移动次数不超过数组的长度)。
Returns all elements in a dimension array to the right(requires the number of moves not to exceed the length of the array).
算法分析:
- 为了达到总移动次数不超过数组长度的要求,每个元素都必须且只能经过一次移动就到达目标位置。
- In order to achieve the requirement that the total number of moves does not exceed the length of the array, each element must and can only reach the target position after one movement.
- 首先备份 a[0] 的值,然后计算应移动到 a[0] 的元素的下标 p,并将 a[p] 的值移动至 a[0];接着计算应移动到 a[p] 的元素下标 q,并将 a[q] 的值移至 a[p] ;依此类推,直到将 a[0] 的备份移到正确的位置。若此时移动到位的元素个数已为 n ,则结束,否则,需再备份 a[1] 的值,重复上述过程,直到将所有元素都移到目标位置为止。
- First backup a[ 0] , and then the calculation should be moved to a[ 0] The subscript P of the element and will a[ P] The value moves to a[ 0] :: Then the calculation should be moved to a[ P] The element subscript Q and will a[ Q] The value is moved to a[ P] :: And so on until a[ 0] The backup is moved to the correct location. If the number of elements in place is N at this time, it ends, otherwise, you need to back up a[ 1] , repeat the above procedure until all elements are moved to the target position.
#include<stdio.h>
#define N 10
int main()
{
int a[N];
int k,i,j,temp,t,count;
printf("Please enter 10 elements of array a:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Please enter a flat number of digits:");
scanf("%d",&k);
count=0;
k=k%n;
if(k!=0)
{
i=0;
while(count<n)
{ j=i;
t=i;
temp=a[i];
while(j=(j+n-k)%n)!=i)
{ a[t]=a[j];
t=j;
count++;
}
a[t]=temp;
count++;
i++;
}
}
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}