编程珠玑2.4

对于字符串,循环左移i位。比较三次旋转算法 和 杂技算法 的运行时间。

结果表明,三次旋转算法用时很少,杂技算法因为内存间隔访问、判断记录开销等用时相对很多。


#include <iostream>
#include <string>
#include <time.h>
using namespace std;
#define MAXLEN 1000000
bool flag[MAXLEN];
void acroAlgorithm(char *s,int i){
    int n=(int)strlen(s);
    i=i%n;
    char t;
    memset(flag, 0,sizeof(flag));
    for(int j=0;j<i;j++){
        if(!flag[j]){
            t=s[j];
            int pre=j;
            int cur=(pre+i)%n;
            flag[j]=1;
            while(cur!=j){
                s[pre]=s[cur];
                flag[cur]=1;
                pre=cur;
                cur=(pre+i)%n;
            }
            s[pre]=t;
        }
    }
}
void reverseMe(char *s,int b,int e){
    char t;
    while(b<e){
        t=s[b];
        s[b]=s[e];
        s[e]=t;
        b++;e--;
    }
}
void reverseAlgorithm(char *s,int i){
    int n=(int)strlen(s);
    i=i%n;
    reverseMe(s, 0,i-1);
    reverseMe(s,i,n-1);
    reverseMe(s,0,n-1);
}
int main(){
    char s1[] = "abcdefghijglmnopkrstuvwxyzabcdefghijglmnopkrstuvwxyzabcdefghijglmnopkrstuvwxyz";
    char s2[] = "abcdefghijglmnopkrstuvwxyzabcdefghijglmnopkrstuvwxyzabcdefghijglmnopkrstuvwxyz";
    clock_t start,end;
    start = clock();
    acroAlgorithm(s1, 4);
    end = clock();
    cout<<(end-start)<<endl;
    cout<<s1<<endl;
    start = clock();
    reverseAlgorithm(s2, 4);
    end = clock();
    cout<<(end-start)<<endl;
    cout<<s2<<endl;
}

运行结果:

1143

4

你可能感兴趣的:(编程珠玑)