实例四十六:数组元素平移

实例四十六:数组元素平移

问题描述:
将一维数组中的所有元素循环向右平移若干位(要求移动次数不超过数组的长度)。
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;
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值