-8

What is the C code for mergeing two unsorted arrays without using a 3rd array. Eg array1={1,3,5,7} array2={2,4,6} Output should be array1={1,2,3,4,5,6,7}.

This is the code i have written.But this doesnt work if the number of array elements are same in both arrays.kindly help me in fixing this bug.

void merge(int a[],int b[],int ele1,int ele2)
{
int i,j,k,ele3;
ele3=ele1+ele2;
for(i=1,k=0;k<ele2;i=i+2)
{
    j=ele1;
    while(j>=i)
    {
        a[j]=a[j-1];
        j--;
    }
    a[j+1]=b[k];
    k++;ele1++;
}
for(i=0;i<ele3;i++)
printf("%d ",a[i]);
 }

main() 
{ 
int a[]={1,3,5},b[]={2,4},ele1,ele2; 
ele1=sizeof(a)/sizeof(a[0]); ele2=sizeof(b)/sizeof(b[0]); 
merge(a,b,ele1,ele2); 
} 
  • 3
    Does any one the first 2 arrays have sufficient space to hold? – Kiran Kumar Dec 22 '16 at 06:01
  • Nothing is mentioned in the question.This was an interview question I got.They said its all ur wish wen I asked if there is memory – Nikhil P.R Dec 22 '16 at 06:03
  • You say unsorted arrays, but the example given is for sorted arrays. – Rishikesh Raje Dec 22 '16 at 06:11
  • 1
    Possible duplicate of [Merging two arrays without using extra space](http://stackoverflow.com/questions/4903585/merging-two-arrays-without-using-extra-space) – Praburaj Dec 22 '16 at 06:13
  • If that is exactly how your interview question is proposed, I'd be more concerned with the facilitation of requirements from your prospective future employer than actually solving the problem. If the **real** problem is performing a merge-sort in-place, [that subject has been widely discussed and solutions proposed for 30+ years](http://stackoverflow.com/questions/2571049/how-to-sort-in-place-using-the-merge-sort-algorithm). To say the algorithms to accomplish it are non-trivial would be a gross understatement. – WhozCraig Dec 22 '16 at 07:18
  • @NikhilP.R Have you written any code for this? – RoadRunner Dec 22 '16 at 07:31
  • hey sorry for not responding..i was first time to this blog.so i din knw anything. – Nikhil P.R Dec 24 '16 at 15:35
  • void merge(int a[],int b[],int ele1,int ele2) { int i,j,k,ele3; ele3=ele1+ele2; for(i=1,k=0;k=i){ a[j]=a[j-1]; j--; } a[j+1]=b[k]; k++;ele1++; } for(i=0;i – Nikhil P.R Dec 24 '16 at 15:40

1 Answers1

1

It can be done easily if any one of the array is capable of holding all elements, Otherwise it can be done if any one of the array is dynamic array, In case of dynamic array we can change the size of the array by using realloc so, after that we merge it easily

The solution will be like [Not tested, Its likely answer]

void merge(int ar1[], int ar2[])
{
  int len = ar1.length;
  int totalLength= (ar1.length+ar2.length);
  ar1= (int*)realloc(ar1,(totalLength)*sizeof(int));

  for (int i=len,index=0; i<totalLength; i++)
  {

    ar1[i]=ar2[index];
    index++;

  }
}
Kiran Kumar
  • 1,033
  • 7
  • 20