n 元一维向量旋转问题(编程珠机) 第二章问题B

/*
 * method No_1
 * using a temp to store x[0],then x[0] = x[i] ,x[i] = x[2i] ......until ki>=n,then x[(k-1)i] = x[0]
 * then dealing with x[1],x[2] ........x[i-1]
 */

int gcd(int x ,int y)
{
	if(x==0)return y;
	if(y==0)return x;
	if(x>y)return gcd(x%y,y);
	return gcd(x,y%x);
}

void vector_reversal(char* str, int n, int rotdist)
{
	int len = gcd(n,rotdist);
	int i;
	for(i =0;i<len;i++)
	{
		int temp = str[i];
		int j = i;
		while(1)
		{
			int k = j+rotdist;
			if(k>=n)
				k-=n;
			if(k==i)
				break;
			str[j] = str[k];
			j = k;
		}
		str[j] = temp;
	}
}



/*
 * method No_2
 * recursive  the programming requirs that we can reversal vector ab into ba, so if len(a) < len(b),we can divide b into b1,b2,
 * the vector will be ab1b2,and len(a) == len(b2),swap the memory a and b2,the vector changes to be b2b1a, and a has located at right
 * place ,the next is to deal with b2b1,which is suposed be b1b2,so , it's  very easy to solve it with a recursive programme
 * the method is same to dealing with len(a)<(len)b, when len(a) > len(b), and when len(a) == len(b) ,swap the memory
 */

void swap(char *p1_start,char *p2_start,int len)
{
	while(len--)
	{
		char temp = p1_start[len];
		p1_start[len] = p2_start[len];
		p2_start[len] = temp;
	}

}

void vector_reversal(char *base,int n, int i)
{
	if(i == n-i)
	{
		swap(base,base+i,i);
		return ;
	}
	if(i < n-i)
	{
		swap(base,base+n-i,i);
		vector_reversal(base,n-i,i);
	}
	else{
		swap(base+2*i-n,base+i,n-i);
		vector_reversal(base,i,2*i-n);
	}
}



/*
 * methond No_3 , two times reversal
 * the vector is ab,which is supposed to be changed into ba,
 * so reverse a into a' , change b into b' ,then change (a'b') into (a'b')' = ba
 */
void swap(char *a,char *b)
{
	char temp = *a;
	*a = *b;
	*b = temp;
}
void reversal(char *start,char *end)
{
	char *ptr_start = start;
	char *ptr_end = end;
	while(ptr_start < ptr_end)
	{
		swap(ptr_start,ptr_end);
		ptr_start++;
		ptr_end--;
	}
}
void vector_reversal(char *base,int n, int i)
{
	reversal(base,base+i-1);
	reversal(base+i,base+n-1);
	reversal(base,base+n-1);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值