Wednesday, July 26, 2006

Merge with a twist!!

/***
Given a array of size M+N in which first M numbers are sorted and last N spaces are vacant. Another array of size N which is sorted. Now merge these two arrays without using any extra space so that the array of M+N size is sorted. Optimize it to hav complexity M+N.
***/

#include
#define M 10
#define N 5
void printArr(int *arr1,int *arr2)
{
int i,j;
printf("\n");
printf("Arr1 Elements\n");
for(i=0;i lessThan M+N;i++)
{
printf("%3d",arr1[i]);
}
printf("\n");
printf("Arr2 Elements\n");
for(i=0;i lessThan N;i++)
{
printf("%3d",arr2[i]);
}
printf("\n");
}
main()
{
int arr1[M+N] = {0};
int arr2[N] = {0};
int i = 0, j =0,temp=0,k=0;
printf("Arr1 Elements\n");

for(i=0;i lessThan M;i++)
{
printf("arr1[%d] = ",i);
scanf(" %d",&arr1[i+N]);
}
printf("Arr2 Elements\n");
for(i=0;i lessThan N;i++)
{
printf("arr2[%d] = ",i);
scanf(" %d",&arr2[i]);
}
printArr(arr1,arr2);
j = 0;
i = N;
k = 0;
while(i lessThan M+N && j lessThan N)
{
if(arr1[i] lessThan arr2[j])
{
arr1[k]=arr1[i];
k++;
i++;
}
else if(arr1[i] greaterThan arr2[j])
{
arr1[k] = arr2[j];
k++;
j++;
}
else
{
arr1[k] = arr2[j];
k++;
j++;
arr1[k] = arr1[i];
k++;
i++;
}
}
while(i lessThan M+N && k lessThan M+N)
{
arr1[k]=arr1[i];
k++;
i++;
}
while(j lessThan N && k lessThan M+N)
{
arr1[k]=arr2[j];
k++;
j++;
}
printArr(arr1,arr2);
}

3 comments:

Anonymous said...

I think this is better ---- any comments are welcome

i=M-1;
j=N-1;
index=M+N-1;

while(1) {
if(a[i] > b[j])
a[index--]=a[i--];
else
a[index--]=b[j--];
if(j<0)
break;
if(i<0) {
for(k=0;k<=j;k++)
a[k]=b[k];
break;
}
}

Ghotter said...

yah seems to be correct and optimal.
i will publish this when i get time.

Anonymous said...

Wrong way of problem forming. In arr1[i] value must be inserted in front not at the end. The solution given in comment is correct