向量旋转算法《编程珠玑》第二章笔记

只需要公约数趟for循环便可以旋转完毕。

如果是rotdist=2,i=0那么交换依次就是2,4,6,所以需要第二次i=1,依次交换3,5,7便可

如果是rotdist=3,i=0,交换3,6,然后就是9因为大于总数8,所以从9-8=1继续交换,依次是1,4,7,之后的10大于8所以从10-8=2继续开始依次是2,5 结束。

记录的不太清楚,下面是代码实现。

	public static void main(String[] args) {
		System.out.println(rotate(new char[]{'a','b','c','d','e','f','g','h'},3));
	}
	//左旋转rotdist位置
	public static char[] rotate(char[] x,int rotdist){
			for(int i=0;i<gcd(rotdist,x.length);i++){
			char temp=x[i];
			int j=i;
			while(true){
				int k=j+rotdist;
				if(k>=x.length)
					k -= x.length;
				if( k == i)
					break;
				x[j] = x[k];
				j=k;
				System.out.println(x);
			}
			x[j]=temp;
			}
		return x;
	}
	//求最大公约数
	public static int  gcd(int i,int j){
		while( i !=j){
			if(i>j) i-=j;
			else j-=i;
		}
		return i;
	}


还有一种方法:


	public static char[] reverse(char[] x,int a,int b){
		char temp;
		while(a<b){
			temp=x[a];
			x[a]=x[b];
			x[b]=temp;
			a++;
			b--;
		}
		return x;
	}

	public static void main(String[] args) {
		char[] x = new char[]{'a','b','c','d','e','f','g','h'};
		int rot=3,n=x.length;
		x=reverse(x,0,rot-1);
		x=reverse(x,rot,n-1);
		x=reverse(x,0,n-1);
		System.out.println(x);
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜欢编程的网管

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值