This is the personal note after reading the perfect shuffle of July blog.
Title: Put a1,a2,a3,a4,..., an-1 an,b1,b2,b3,..., bn-1,bn into A1,B1,A2,B1,..., an,bn. Requires a time complexity of O (n), and a space complexity of O (1).
1. Position substitution algorithm: B is a newly opened array, but the time complexity is O (n) and the spatial complexity is O (n).
void perfectshuttle (int a[],int n) { int n2=n*2, b[n]; for (int i=1; i<=n2;i++) b[(2*i)% (n2+1 )]=a[i]; for (int i=1; i<=n2;i++) a[i]=b[i];}
2. Regardless of whether you n are odd or even, the elements of each position will change to the (2*i)% (2n+1) element:
Array subscript starting from 1, the From is the head of the Circle, MoD is to modulo the number mod should be 2 * n + 1, time complexity O (lap length)
void Cycleleader (int a[],intfrom,int mod) { for (int i=from *2%mod;i!=from; i=i*2MoD) swap (A[i], a[ from]);
3. Divine Conclusion: 2*n= (3^k-1), you can determine the number of rings and the starting position of their respective heads
Perfect shuffle algorithm, its algorithm flow is :
Input array a[1..2 * n]
Step 1 found 2 * m = 3^k- 1 makes 3^k <= 2 * N < C17>3^ (k +1)
Step 2 a[m + 1. n + m] that part of the loop moves m bit
step 3 for each i = Span class= "S4" >0,1,2.1,3^i is the head of a circle, doing cycle_leader algorithm, the array length is m 2 * m + 1 modulo
Step 4 The back part of the array a[2 * m + 1. 2 * N] continue to use this algorithm , which is equivalent to n reduced m
//Flip String time complexity O (to-from)voidReverseint*a,int from,intTo ) { for(; from< to; ++ from, --to ) swap (a[ from],a[to]);}//loop right shift num bit time complexity O (n)voidRightrotate (int*a,intNumintN) {reverse (A,1Nnum); Reverse (A, n-Num +1, N); Reverse (A,1, n);}
voidPerfectShuffle2 (int*a,intN) { intN2, M, I, K, t; while(N >1 ) { //Step 1N2 = n *2; for(k =0, M =1; n2/m >=3; ++k, M *=3) ; M/=2; //2m = 3^k-1, 3^k <= 2n < 3^ (k + 1)//Step 2Right_rotate (A +m, M, N); //Step 3 for(i =0, t =1; I < K; ++i, T *=3) {Cycleleader (A, T, M*2+1); } //Step 4A + = M *2; N-=m; } //n = 1Swap (a[1],a[2]);}
Perfect Shuffle algorithm