Wednesday, November 11, 2009

Write a C program to merge two unsorted one dimensional arrays in descending order

Write a program to merge two unsorted 1D arrays in descending order
Note: Define the sizes of each array as a constant i.e. your program should run for arrays of any size.



#include(stdio.h)  // note '<' & '>' in place of '(' & ')'
            // size of the array is 20
#define MAX 20
int main()
{
 int f[MAX],s[MAX];
 int m,n; // to read the size of two arrays
 int i,j,temp;
 clrscr();
 printf("Enter the 1st array size(1-20) :");
 scanf("%d",&m);
 printf("Enter the 2nd array size(1-20) :");
 scanf("%d",&n);
 printf("\nEnter the 1st array elements:");
 for(i=0; i< m; i++)
   scanf("%d",&f[i] );


 printf("\nEnter the 2nd array elements:");
 for(j=0; j< n; j++)
   scanf("%d", &s[j] );


 for(j=0; j< n; j++)  // to store 's' elements to 'f'
 {
    f[i]=s[ j];
    i++;
 }
 printf("\nBefore descending, the merged array is:\n");
 for(i=0; i< m+n; i++)
    printf("%5d",f[i] );


 for(i=0; i< m+n; i++)// to arrange the 'f' elements in Descending oder
 {
    for(j=i; j< (m+n)-1; j++)
    {
       if(f[i]< f[ j+1])
       {
     temp=f[i];
     f[i]=f[ j+1];
     f[ j+1]=temp;
       }
    }
 }
 printf("\nAfter descending, the merged array is:\n");
  for(i=0; i< m+n; i++)
    printf("%5d",f[i] );
getch();
 return 0;
}


Output:-


Enter the 1st array size(1-20) :4
Enter the 2nd array size(1-20) :5


Enter the 1st array elements:12
3
45
12


Enter the 2nd array elements:78
5
43
1
23


Before descending, the merged array is:
   12    3   45   12   78    5   43    1   23
After descending, the merged array is:
   78   45   43   23   12   12    5    3    1

No comments:

Post a Comment