Yahoo Interview Question
Software Engineer / DevelopersThis in an O(n log n) solution.
Explanation :
We divide the array in four sections:[X,Y|A,B]
It is easy to see that with swaps we can modify it to the form [X,A|Y,B].
Now do recursion to solve [X|A] and [Y|B] separately,essentially using divide and conquer.
-------------------------------------
For example:
Original Array: [X,Y|A,B] = { 1,2,3,4,5,6,7,8,a,b,c,d,e,f,g,h }
where X = { 1,2,3,4 }, Y = { 5,6,7,8 }, A = { a,b,c,d }, B = {e,f,g,h}
Now, swap sections Y and A
New array : [X,A|Y,B] = { 1,2,3,4,a,b,c,d,5,6,7,8,e,f,g,h }
We now have divided original problem in to two similar sub problems by doing n/2 swaps.
We can use recursion to solve the sub problems now.
-------------------------------------
Complexity Analysis :
T(n) = 2T(n/2) + O(n)
=> T(n) = O(n log n)
There are also other ways of doing this in O(n log n), for instance one can define the appropriate comp() function that compares the integers and characters and then just sort the array with respect to that function.
static void swap(int arr[],int i,int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
static void rollBack(int arr[],int right,int left){
for(int i=right;i>left;i--)
arr[i] = arr[i-1];
}
static void reArrange(int array[]){
int index = array.length/2;
for(int i=1;i<array.length-1;i+=2){
int tmp = array[i];
swap(array,i,index);
rollBack(array, index++, i);
array[i+1] = tmp;
}
}
void rearrange(int A[],int begin,int end)
- Manish October 16, 2010{
if(begin+1==end)
return;
if(begin<end){
int mid=(begin+end)/2;
int r1=(begin+mid)/2;
int r2=(mid+1+end)/2;
int d=mid-begin;
int i,j;
if(d%2!=0){
j=mid+1;
for(i=r1+1;i<=mid;i++)
swap(&A[i],&A[j++]);
rearrange(A,begin,mid);
rearrange(A,mid+1,end);
}
else{
j=mid+1;
for(i=r1;i<=mid;i++)
swap(&A[i],&A[j++]);
swap(&A[mid],&A[mid+1]);
rearrange(A,begin,mid-1);
rearrange(A,mid+2,end);
}
}
}