Jan 3, 2009

Explain in place merging of two sorted arrays? In place merge sort O(N^2), anyway, you can use binary search instead of brute force iteration, but whe

Explain in place merging of two sorted arrays?
In place merge sort O(N^2), anyway, you can use binary search instead of brute force iteration, but when you find the position, you still need to move all elements before the inserted element


insert(int i,int len,int b[])
{
int val=b[i];
for(int j=i+1;j<len;j++)
{
if(val>b[j])
{
int temp=val;
val=b[j];
b[j]=val;
}
else break;
}
}
void InPlcaeMergeSort(int a[],int b[], int len)
{
for(int i=0;i<len;i++)
{
if(a[i]>b[i])
{
int temp=a[i];
a[i]=b[i];
b[i]=temp;
insert(i,len,b);
}
else
{
if(a[i+1]<b[i])
{
int temp=a[i+1];
a[i+1]=b[i];
b[i]=temp;
insert(i+1,len,a);
}
}
cout<<a[i]<<" "<<b[i]<<endl;
}
}


or
If one array is big enough to contain all elements of two arrays, you can merge the small array into big one in O(n)

No comments:

Post a Comment