Merging of arrays

How to merge two arrays?

Two sorted arrays can be merged this way:

  1. create an array of size n1+n2 where n1 and n2 are sizes of sorted arrays given
  2. place a pointer (say i) at start of first array and another pointer at start of second array(say j) and third pointer at start of resultant array(say k)
    i=0,j=0,k=0
    now if(a1[i]<a2[j])
    then result[k]=a1[i],k++,i++;
    else
    result[k]=a2[j],k++,j++;
    to this until i or j reaches to end.
    after this it may be possible that some elements remain in one of arrays, so just put these elements in your result array by doing:
    while(i<n1)
    result[k]=a1[i],k++,i++;
    while(j<n2)
    result[k]=a2[j],k++,j++;

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.