program for merge sort...
#include<conio.h>
#include<iostream.h>
#include<stdio.h>
void main()
{
int i,j,n,p,m,a[20],b[20],c[40],k;
clrscr();
cout<<"Enter the limit 1\n";
cin>>m;
cout<<"Enter the elements\n"; /* 2 arrays must be in sorted order otherwise you make them sorted..*/
for(i=0;i<m;i++)
{
cin>>a[i];
}
cout<<"Enter the limit 2\n";
cin>>n;
cout<<"Enter the elements\n";
for(j=0;j<n;j++)
{
cin>>b[j];
}
i=0;
j=0;
k=0;
while((i<m)&&(j<n))
{
if(a[i]<=b[j])
{
c[k]=a[i];
i++;
k++;
}
else
{
c[k]=b[j];
k++;
j++;
}
}
while(i<m)
{
c[k]=a[i];
k++;
i++;
}
while(j<n)
{
c[k]=b[j];
k++;
j++;
}
cout<<"sorted elements\n";
for(i=0;i<n+m;i++)
{
cout<<c[i]<<" ";
}
getch();
}
The mergesort algorithm is based
on the classical divide-and-conquer paradigm. It operates as
follows:
#include<conio.h>
#include<iostream.h>
#include<stdio.h>
void main()
{
int i,j,n,p,m,a[20],b[20],c[40],k;
clrscr();
cout<<"Enter the limit 1\n";
cin>>m;
cout<<"Enter the elements\n"; /* 2 arrays must be in sorted order otherwise you make them sorted..*/
for(i=0;i<m;i++)
{
cin>>a[i];
}
cout<<"Enter the limit 2\n";
cin>>n;
cout<<"Enter the elements\n";
for(j=0;j<n;j++)
{
cin>>b[j];
}
i=0;
j=0;
k=0;
while((i<m)&&(j<n))
{
if(a[i]<=b[j])
{
c[k]=a[i];
i++;
k++;
}
else
{
c[k]=b[j];
k++;
j++;
}
}
while(i<m)
{
c[k]=a[i];
k++;
i++;
}
while(j<n)
{
c[k]=b[j];
k++;
j++;
}
cout<<"sorted elements\n";
for(i=0;i<n+m;i++)
{
cout<<c[i]<<" ";
}
getch();
}
No comments:
Post a Comment