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?