Algorithm: Detailded CyclicShift Solution One of Programming Pearls (2nd)

This artical will show you the detailed implementation of Cyclic Shift which is mentioned in Programming Pearls (2nd). In that book on Page 11, Column2.1, Question B,

Rotate a one-dimensional vector of n elements left by i positions. For instance, with n=8 and i=3, the vector abcdefgh is rotated to defghabc. Simple code uses an n-element intermediate vector to do the job in n steps. Can you rotate the vector in time proportional to n using only a few dozen bytes of storage?

author introduced one solution likes delicate juggling act. But I found this way is a little hard to understand. So based on standard answer behind book, I create a diagram and a implementation codes to clear this alforithm.

Diagram:

Rotate

C++ Codes:

// CyclicShift1.cpp : Defines the entry point for the console application. // #include <iostream.h> #include <string.h> int gcd(int a,int b) { if(a<b) { int temp = a ; a = b ; b = temp ; } while(b!=0) { int temp = a%b ; a = b ; b = temp ; } return a ; } void CyclicShift(char str[], int rotdist, int len) { for(int i=0 ; i<gcd(rotdist,len); i++) { int t=str[i] ; int j=i ; int k=0 ; while(1) { k = k+rotdist ; if(k>=len) k = k-len ; if(k==i) break; str[j] = str[k] ; j = k ; } str[j] = t ; } } int main(int argc, char* argv[]) { char str[]={'a','b','c','d','e','f','g','h','/0'} ; int len = sizeof(str)/sizeof(char)-1 ; CyclicShift(str,3,len) ; cout<<str<<endl ; return 0; }

For any question, please contact me.

yexianyi@hotmail.com

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值