#include<iostream.h>
#include<conio.h>
void mergesort(int[],int,int);
void merge(int[],int,int,int);
void main()
{
int a[10],p,q,r,i,n;
clrscr();
cout<<"Enter the number of elements";
cin>>n;
p=0;
r=n-1;
cout<<"Enter the array";
for(i=0;i<n;i++)
{
cin>>a[i];
}
mergesort(a,p,r);
cout<<"The sorted array is:";
for(i=0;i<n;i++)
{
cout<<"\n"<<a[i];
}
getch();
}
void mergesort(int a[],int p,int r)
{
if( p < r)
{
int q=(p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r) ;
merge(a,p,q,r);
}
}
void merge(int a[],int p,int q,int r)
{
int c[10];
int i=p;
int j=q+1;
int k=p;
while((i<=q)&&(j<=r))
{
if(a[i]<a[j])
{
c[k]=a[i];
i=i+1;
k=k+1;
}
else
{
c[k]=a[j];
j=j+1;
k=k+1;
}
}
while(i<=q)
{
c[k] =a[i];
i=i+1;
k=k+1;
}
while(j<=r)
{
c[k]=a[j];
j=j+1;
k=k+1;
}
int l=p;
while(l<=r)
{
a[l]=c[l];
l=l+1;
}
}
#include<conio.h>
void mergesort(int[],int,int);
void merge(int[],int,int,int);
void main()
{
int a[10],p,q,r,i,n;
clrscr();
cout<<"Enter the number of elements";
cin>>n;
p=0;
r=n-1;
cout<<"Enter the array";
for(i=0;i<n;i++)
{
cin>>a[i];
}
mergesort(a,p,r);
cout<<"The sorted array is:";
for(i=0;i<n;i++)
{
cout<<"\n"<<a[i];
}
getch();
}
void mergesort(int a[],int p,int r)
{
if( p < r)
{
int q=(p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r) ;
merge(a,p,q,r);
}
}
void merge(int a[],int p,int q,int r)
{
int c[10];
int i=p;
int j=q+1;
int k=p;
while((i<=q)&&(j<=r))
{
if(a[i]<a[j])
{
c[k]=a[i];
i=i+1;
k=k+1;
}
else
{
c[k]=a[j];
j=j+1;
k=k+1;
}
}
while(i<=q)
{
c[k] =a[i];
i=i+1;
k=k+1;
}
while(j<=r)
{
c[k]=a[j];
j=j+1;
k=k+1;
}
int l=p;
while(l<=r)
{
a[l]=c[l];
l=l+1;
}
}
Thanks! I would like to Keep in touch with you to understand programming easily.
ReplyDeletethanks
Deletein function merge() no need to initialize the variable k to p. it can be done by initializing to 0. the code will look like...
ReplyDeletevoid merge(int arr[],int l, int m, int h)
{
int temp[100];
int i=l;
int j=m+1;
int k=0;
while((i<=m)&&(j<=h))
{
if(arr[i]<arr[j])
{
temp[k++]=arr[i++];
}
else
{
temp[k++]=arr[j++];
}
}
while(i<=m)
temp[k++]=arr[i++];
while(j<=h)
temp[k++]=arr[j++];
int c=l;
int d=0;
while(c<=h)
arr[c++]=temp[d++];
}
otherwise very nice code...
seriously man you are still using iostream.h that have been depreciated so long.
ReplyDeletebeginners can understand it quickly i think
ReplyDeleteThank you very much! Greatly helped!
ReplyDeleteEasy c++ programming
ReplyDeleteEasy to understand. Thanks a lot.
ReplyDelete