A is an array sorted in ascending order. B is an array sorted in descending order. Merge A and B into C so that C is in ascending order.

#include <stdio.h>


int main()
{
    int A[]={17,24,31,39,44}, B[]={49,36,29,20,18,13};
    int sizea = sizeof(A)/sizeof(A[0]);
    int sizeb = sizeof(B)/sizeof(B[0]);
    int C[sizea+sizeb], k=0, m=sizeb-1, count=0;
   
        //print array
    printf("\nArray A\n");
    for(int i=0; i<sizea; i++)
        printf("%d\t", A[i]);
    printf("\n");
        //print array
    printf("\nArray B\n");
    for(int i=0; i<sizeb; i++)
        printf("%d\t", B[i]);
    printf("\n");
   

    //copy the array
    while (k<sizea && m>0) {
        if (A[k] <= B[m]) {
            C[count++] = A[k];
            k++;
        }
        else {
            C[count++] = B[m];
            m--;
        }
    }
    while (k<sizea) {
        C[count++] = A[k];
        k++;
    }
    while (m>=0) {
        C[count++] = B[m];
        m--;
    }
   
    //print array
    printf("\nArray C\n");
    for(int i=0; i<sizea+sizeb; i++)
        printf("%d-", C[i]);
    printf("\n");

    return 0;
}
Output:
Array C                                                                                                         
13-17-18-20-24-29-31-36-39-44-49-

Comments

Popular posts from this blog

An array A contains integers that first increase in value and then decrease in value. It is unknown at which point the numbers start to decrease. Write efficient code to copy the numbers in A to another array B so that B is sorted in ascending order.

Recursion examples with integers