interclasare divide et impera

Sortarea prin interclasare (merge-sort)

mergesort

Utilizand metoda divide et impera, sa se sorteze prin interclasare un sir

#include<iostream.h>
int a[20],n;

void mergesort(int i,int m,int j)

{int b[20],x=i,k=1,y=m+1;
while(x<=m && y<=j)
if (a[x]<a[y])
b[k++]=a[x++];
else
b[k++]=a[y++];
while (x<=m)
b[k++]=a[x++];
while (y<=j)
b[k++]=a[y++];
int t=i;
for (k=1;k<=(j-i)+1;k++)
a[t++]=b[k];
}

void divimp(int i,int j)
{if (i<j)
{int m=(i+j)/2;
divimp(i,m);
divimp(m+1,j);
mergesort(i,m,j);}
}

void main()
{
cout<<“n=”;
cin>>n;
for(int i=1;i<=n;i++)
{cout<<“a[“<<i<<“]=”;
cin>>a[i];
}
divimp(1,n);
cout<<“vectorul sortat este: “<<endl;
for(i=1;i<=n;i++)
cout<<a[i]<<‘ ‘;
}

interclasare

Se citesc doi vectori cu componente numere naturale.Fiecare vector are elementele sortate crescator. Se cere sa se construiasca un al treilea vector care contine elementele celor doua in ordine crescatoare.

#include<iostream.h>
void main(void)
{
int i,n,j,m,k;
float x[50],y[50],z[100];
cout<<“Dati numarul de elemente ale vectorului x “;cin>>n;
for(i=1;i<=n;i++)
{
cout<<“x[“<<i<<”]= “;
cin>>x[i];
}
cout<<“Dati numarul de elemente alevectoruluii y “;cin>>m;
for(j=1;j<=m;j++)
{
cout<<“y[“<<j<<”]= “;
cin>>y[j];
}
i=1;j=1;k=0;
while( (i<=n) && (j<=m) )
if(x[i]<y[j]){k++;z[k]=x[i];i++;}
else {k++;z[k]=y[j];j++;}
if(i<=n) for(j=i;j<=n;j++) {k++;z[k]=x[j];}
else for(i=j;i<=m;i++) {k++;z[k]=y[i];}
cout<<endl<<“Vectorul z cu elementele interclasate este “;
for(i=1;i<=k;i++) cout<<z[i]<<” ”;
}