C Program To Merge Two Sorted Arrays Element

In this program, You will take two sorted arrays from the user and merge these arrays in sorted order, and stored them in the third array.

Merge Two Sorted Arrays program

#include<stdio.h>
int main()
{
    int sort_a[100],a1[50],b1[50],i,j,k,n,m;
    printf("enter size of first array:");
    scanf("%d",&n);
    printf("enter element in first array a1 in sorted order:");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a1[i]);
    }
    printf("enter size of second array:");
    scanf("%d",&m);
    printf("enter element in second array b1 in a sorted order:");
    for(i=0;i<m;i++)
    {
        scanf("%d",&b1[i]);
    }
    i=j=k=0;
    while(i<(m+n))
    {
        if(j<=m && k<=n)
        { 
             /*check if curent element of array a1 is less
            than current element of array b1 if true 
            store current element of array a1 and increment
             array a1 index. otherwise do same with array b1 */
            if(a1[j]<b1[k])
            {
                sort_a[i]=a1[j];
                i++;
                j++;
            }
            else
            {
               sort_a[i]=b1[k];
               i++;
               k++;  
            }    
        }
        /* store remaining element of second array b1 */
        else if(j==m)
        {
            sort_a[i]=b1[k];
            k++;
            i++;
        }
        /* store remaining element of first array a1 */
        else
        {
            sort_a[i]=a1[j];
            j++;
            i++;
        }
    }
    printf("merge array:");
    for(i=0;i<(m+n);i++)
    {
       printf("%d\t",sort_a[i]); 
    }
    return 0;
}

output

enter element in first array a1 in sorted order:1 4 5 7 9
enter size of second array:3
enter element in second array b1 in a sorted order:2 3 7
merge array:1   2       3       4       5       7       7       9