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:
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.