Showing posts with label merge sort. Show all posts
Showing posts with label merge sort. Show all posts

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)

Dec 24, 2008

Difference between merge and quick, when to use which?

Difference between merge and quick, when to use which?

Merge sort is stable, always O(nlog(n)), but need external storage O(n)
Quick sort is in place sorting with O(nlogn), but the worst case performance for quick sort is O(n^2)
Merge sort and heap sort is stable, others are not stable