Practicing recursion and D&C and a frequent problem seems to be to convert the array:
[a1,a2,a3..an,b1,b2,b3...bn]
to [a1,b1,a2,b2,a3,b3...an,bn]
I solved it as follows (startA
is the start of a
s and startB
is the start of b
s:
private static void shuffle(int[] a, int startA, int startB){
if(startA == startB)return;
int tmp = a[startB];
shift(a, startA + 1, startB);
a[startA + 1] = tmp;
shuffle(a, startA + 2, startB + 1);
}
private static void shift(int[] a, int start, int end) {
if(start >= end)return;
for(int i = end; i > start; i--){
a[i] = a[i - 1];
}
}
But I am not sure what the runtime is. Isn't it linear?
Let the time consumed by the algorithm be T(n)
, and let n=startB-startA
.
Each recursive invokation reduces the run time by 1 (startB-startA
is reduced by one per invokation), so the run time is T(n) = T(n-1) + f(n)
, we only need to figure what f(n)
is.
The bottle neck in each invokation is the shift()
operation, which is iterating from startA+1
to startB
, meaning n-1
iterations.
Thus, the complexity of the algorithm is T(n) = T(n-1) + (n-1)
.
However, this is a known Theta(n^2)
function (sum of arithmetic progression) - and the time complexity of the algorithm is Theta(N^2)
, since the initial startB-startA
is linear with N
(the size of the input).