C Program to merge and sort two arrays

How to write a C Program to merge and sort two arrays in C Programming Language ?

This C Program to merge and sort two arrays.

Solution:

  1. #include<stdio.h>
  2. void sort(int a[],int);
  3. void main()
  4. {
  5.         int a[20],c[10],i,m,n,j;
  6.         printf("Enter the no.of elements in 1st array- \n");
  7.         scanf("%d",&m);
  8.         printf("Enter the 1st array - \n");
  9.         for(i=0;i<m;i++)
  10.                 scanf("%d",&a[i]);
  11.         printf("Enter the no.of elements in the 2nd array");
  12.         scanf("%d",&n);
  13.         printf("Enter the 2nd array");
  14.         for(i=0;i<n;i++)
  15.                 scanf("%d",&c[i]);
  16.         sort(a,m);
  17.         printf("1st sorted array - \n");
  18.         for(i=0;i<m;i++)
  19.                 printf("%d, ",a[i]);
  20.         sort(c,n);
  21.         printf("2nd sorted array - \n");
  22.         for(i=0;i<n;i++)
  23.         printf("%d, ",c[i]);
  24.         j=m;
  25.         for(i=0;i<n;i++)
  26.         {a[j]=c[i];
  27.         j++;}
  28.         sort(a,m+n);
  29.         printf("Merged and Sorted array - \n");
  30.         for(i=0;i<m+n;i++)
  31.                 printf("%d, ",a[i]);
  32. }
  33. void sort(int a[],int n)
  34. {
  35.         int i,j,temp;
  36.         for(i=0;i<n;i++)
  37.         {       for(j=i+1;j<n;j++)
  38.                         if(a[i]>a[j])
  39.                         {       temp=a[i];
  40.                                 a[i]=a[j];
  41.                                 a[j]=temp;
  42.                         }
  43.         }
  44. }


Learn More :