[编程珠玑]aha,algorithms

Rotate a one-dimensional vector of n elements left by i positions.

Solution1
 1 void Solution(char* arr,int n,int rotdist)
2 {
3 int i;
4 //循环n和rotdist的最大公约数次
5 for(i=0;i<gcd(n,rotdist);++i)
6 {
7 char t=arr[i];
8 int index=i;
9 while((index+rotdist)%n!=i)
10 {
11 arr[index]=arr[(index+rotdist)%n];
12 index=(index+rotdist)%n;
13 }
14 arr[index]=t;
15 }
16 }

 

Solution2

View Code
 1 //swapthe two segments of the vector ab to be the vector ba,
2 //where a represents the first i elements of x.Suppose a is shorter than b.
3 //Divide b into bl and br so that br is the same length as a.
4 //Swap a and br to transform ablbr into brbla.The sequence a is
5 //in its final place,so we can focus on swapping the two parts of b.
6 char* arr;
7
8 void swap(int s1,int e1,int s2,int e2)
9 {
10 int i,j;
11 for(i=s1,j=s2;i<=e1;++i,++j)
12 {
13 arr[i]=arr[j];
14 }
15 }
16
17 void Solution(char* arr,int start,int end,int rotdist)
18 {
19 int n=end-start+1;
20 if(rotdist==n-rotdist)
21 {
22 swap(start,start+rotdist-1,start+rotdist,end);
23 return;
24 }
25 else if(rotdist<n-rotdist)//左边小
26 {
27 swap(start,start+rotdist-1,end-rotdist+1,end);
28 Solution(arr,start,end-rotdist,rotdist);
29 }
30 else
31 {
32 swap(start,end-rotdist,start+rotdist,end);
33 Solution(arr,end-rotdist+1,end,2*rotdist+start-end-1);
34 }
35 }

 Solution3(Best one)

View Code
1 reverse(0,rotdist-1);
2 reverse(rotdist,n-1);
3 reverse(0,n-1);

 

PS:Solve great common divisor

View Code
 1 int gcd(int i,int j)
2 {
3 while(i!=j)
4 {
5 if(i>j)
6 i=i-j;
7 else
8 j=j-i;
9 }
10 return i;
11 }

 

你可能感兴趣的:(algorithms)