Saturday, February 24, 2024

17. Given two ordered arrays of integers, write a program to merge the two-arrays to get an ordered array.

 #include <stdio.h>

int main()

{

    int n1,n2,n3;            

    int a[20], b[20], c[40];

    printf("Enter the size of first array: ");

    scanf("%d",&n1);

    printf("Enter the array elements: ");

    for(int i = 0; i < n1; i++)      

       scanf("%d", &a[i]);

    printf("Enter the size of second array: ");

    scanf("%d",&n2);

    printf("Enter the array elements: ");

    for(int i = 0; i < n2; i++)      

       scanf("%d", &b[i]);

    n3 = n1 + n2;

    int i = 0, j = 0, k = 0;


    while (i < n1 && j < n2)    

    {

        if (a[i] < b[j])

            c[k++] = a[i++];    

        else

            c[k++] = b[j++];

    }

  

    while (i < n1)    

        c[k++] = a[i++];

  

    while (j < n2)    

        c[k++] = b[j++];

    

    printf("Final array after merging: ");

    for(int i = 0; i < n3 ; i++)       

        printf(" %d ",c[i]);

    return 0;   

}

No comments:

Post a Comment