Home » Sometech » WAP to merge two sorted arrays in ascending order into third array.

WAP to merge two sorted arrays in ascending order into third array.

#include <stdio.h>

#define S 10

#define T 20

void main()

{

   int i,j,k,m,n,r;

    int A[S],B[S],C[T];

printf(“Enter how many elements for array A ? “);

scanf(“%d”,&m);

printf(“Enter array A elements in ascending order : \n”);

for (i = 0; i < m; i++)

{ printf(“A[%d]=”,i);

  scanf(“%d”, &A[i]);

 }

       printf(“Enter how many elements for array B ? “);

scanf(“%d”,&n);

printf(“Enter array B elements in ascending order: \n”);

       for (i = 0; i < n; i++)

{ printf(“B[%d]=”,i);

  scanf(“%d”, &B[i]);

 }

printf(“\narray A is \n”);

 for(i = 0; i < m; i++)

     printf(“%d “, A[i]);

printf(“\narray B is \n”);

       for(i = 0; i < n; i++)

     printf(“%d “, B[i]);

      /*merging */

i=j=k=0;

while(i<m && j<n)

{

        if(A[i]<=B[j])

 { C[k]=A[i];  //copy element from fist array

  i++;

 }

   else

 {

  C[k]=B[j]; //copy element from second array

  j++;

 }

 k++;

}

     if(i==m) //first array has been copied

{

 //copy remaining elements from second array

 for(r=j;r<n;r++)

 {

  C[k]=B[r];

  k++;

 }

}

else // second array has been copied

{

 //copy remaining elements from first array

 for(r=i;r<m;r++)

 {

   C[k]=A[r];

   k++;

 }

}

printf(“\nMerged array C is \n”);

 for(i = 0; i < m+n; i++)

     printf(“%d “, C[i]);

 

getch();

}

Advertisements

SoME Tech

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

%d bloggers like this: