|
void swap(int a[], int b[], n){
int i=0;
int temp; /*O(1) auxiliary space*/
for(; i <n; i++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
void f(int a[], int n, int k){
int first = k+1; /*a[0:k] length*/
int second = n-first; /*a[k+1:n-1]length*/
if(first==0 || second==0)
return;
else if(first <= second){
swap(a,a+first,first);
f(a+first,second,first-1);
}
else{
swap(a,a+second,second);
f(a+second,first,first-second-1);
}
}
Each time is divided into 3 segments: [short, long-short, (k position) short] or [short, (k position) short, long-short]
The two short and short are interchanged, and the remaining two segments recursively after the first short is correct, until long=short, you can also use a loop
Similar to subtraction to find the greatest common divisor, the worst case should be long and short, the greatest common divisor is 1
Let each recursion: a[] length L(i), swap length X(i), then:
2X(0) <L(0) = total length of the array n
2X(1) <L(1) = L(0)-X(0)
2X(i) <L(i) = L(i-1)-X(i-1) = L(0)-X(0)-X(1)-…-X(i-1)
At last:
2X(N) = L(N) = L(N-1)-X(N-1) = L(0)-X(0)-X(1)-…-X(N-1)
Let the average value of X(0) to X(N) be X, because X(0)>X(1)>…>X(N),
So L(i)=L(0)-X(0)-X(1)-…-X(i-1)<L(0)-X-X-…-X=L(0)-i*X
Adding inequalities: 2*(N+1)*X <(N+1)*L(0)-[N(N+1)/2]*X
==> (2+N/2)*X <L(0)=n So the time complexity (N*X*constant) is O(n) |
|