Program to sort out two arrays using merge sort

Friday, March 06, 2020

//program to sort out two arrays using merge sort
#include<iostream.h>
#include<conio.h>
void merge_sort(int A[],int B[],int M,int N,int C[])
{ int i=0,j=0,k=0,p;
  while(i<M&&j<N)
  { if(A[i]<B[j])
{ C[k]=A[i];
i++;
}
else
{ C[k]=B[j];
j++;
}
k++;
  }
  if(i==M)
  { for(p=j;p<N;p++)
{ C[k]=B[p];
k++;
}
  }
  else
  { for(p=i;p<M;p++)
{ C[k]=A[p];
k++;
}
  }
}

void main()
{ clrscr();
  int a[20],m,b[20],n,i,c[20];
  cout<<"\n Enter the number of elements of a:";
  cin>>m;
  cout<<"\n Enter the elements of array a";
  for(i=0;i<m;i++)
  { cout<<"\n Enter a["<<i<<"]:";
cin>>a[i];
  }
  cout<<"\n Array is:";
  for(i=0;i<m;i++)
  cout<<a[i]<<"\t";
  cout<<"\n Enter the number of elements of b:";
  cin>>n;
  cout<<"\n Enter the elements of array b";
  for(i=0;i<n;i++)
  { cout<<"\n Enter b["<<i<<"]:";
cin>>b[i];
  }
  cout<<"\n Array is:";
  for(i=0;i<n;i++)
  cout<<b[i]<<"\t";
  merge_sort (a,b,m,n,c);
  cout<<"\n Sorted and concatinated array is:";
  for(i=0;i<n+m;i++)
  cout<<c[i]<<"\t";
  getch();
}

You Might Also Like

0 Comments

Like us on Facebook

Flickr Images

Flickr Short Films