Tuesday, November 22, 2011

9 Merge Sort


#include<iostream>

using namespace std ;


int merge(int[],int,int[],int,int[]) ;

int main()
{
int A[50], B[50], C[50], mn=0, m, n,i ;

cout<<"\nEnter the no. of elements of 1st array: ";
cin>> m ;

cout<<"\nEnter the 1st array: ";
 for(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(i=0 ; i<n ; i++)
 cin>> B[i] ;
 
merge(A,m,B,n,C) ;
   
cout<<"\nThe merged array is: " ;
 for(i=0 ; i<mn ; i++)
 cout<<C[i]<<" " ;

return 0;


}

int 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++] ;
 }

return 0;

}

No comments:

Post a Comment