Friday, November 4, 2011

Merge Sort

#include<iostream>
using namespace std ;
void merge(int[],int,int[],int,int[]) ;
int main()
{    int A[50], B[50], C[50], mn=0, m, n ;
    cout<<"\nEnter the no. of elements of 1st array: ";
   cin>> m ;
   cout<<"\nEnter the 1st array: ";
   for(int i=0 ; i<m ; i++)
       cin>> A[i] ;
   cout<<"\nEnter the no. of elements of 2nd array: ";
   cin>> n ;
   mn=m+n ;
   cout<<"\nEnter the 2nd array: ";
    for(int i=0 ; i<n ; i++)
       cin>> B[i] ;
      merge(A,m,B,n,C) ;
      cout<<"\nThe merged array is: " ;
      for(int i=0 ; i<mn ; i++)
           cout<<C[i]<<" " ;
return 0; 
}

void merge(int A[],int m,int B[],int n,int C[])
{    int a, b, c;
    for(a=0, b=0, c=0; a<m && b<n; )
   {    if(A[a]<=B[b])     C[c++]=A[a++] ;
           else C[c++]= B[b++] ;
   }
   if(a<m)
       {    while(a<m)
              C[c++] = A[a++] ;
      }
   else
       {    while(b<n)
          C[c++] = B[b++] ;
      }
}

No comments:

Post a Comment