Sunday, 5 June 2011

Merging in arrays program in c++

#include<iostream.h>
void main()
{
int na, nb, ptr, r,s, k,a[50],b[50],c[50];
int i,j,m;
cout<<"Number of element for Array[A] : "; cin>>r;
cout<<"Number of element for Array[B] : "; cin>>s;
cout<<"Array : "<<endl;
for(i=1;i<=r;i++)
{
cout<<"A["<<i<<"] : ";
cin>>a[i];
}
cout<<"\n";
  for(j=1;j<=s;j++)
  {
  cout<<"B["<<j<<"] : ";
  cin>>b[j];
  }
  na = 1;
  nb = 1;
  ptr= 1;
  while(na<=r && nb<=s)
  {
  if(a[na]<b[nb])
  {
  c[ptr] = a[na];
  ptr = ptr +1; na = na+1;
  }
  else
  {
  c[ptr] = b[nb];
  ptr = ptr+1;
  nb= nb+1;
  }
  }
  if(na>r)
  {
  for(k=0;k<=s-nb;k++)
  {
  c[ptr+k]=b[nb+k];

  }
  cout<<"After sorting these two arrays :"<<endl;
  for(i=1;i<=r+s;i++)
  {
  cout<<"Array["<<i<<"] : "<<c[i]<<endl;
  }

  }
  else
  {
  for(k=0;k<=r-na;k++)
  {
  c[ptr+k]=a[na+k];
  cout<<c[k];
  }
    cout<<"After sorting"<<endl;
  for(i=1;i<=r+s;i++)
  {
  cout<<"Array["<<i<<"] : "<<c[i]<<endl;
  }

  }

}
Editing & program by "Shojib"

No comments:

Post a Comment