#include<iostream.h>
#include<conio.h>
#include<values.h>
void merge(int a[],int p,int q,int r)
{
int n1=q-p+1,n2=r-q;
int *l=new int[n1+1];
int *rt=new int[n2+1];
for(int i=0;i<n1;i++)
l[i]=a[p+i];
for(int j=0;j<n2;j++)
rt[j]=a[q+j+1];
l[n1]=MAXINT; //SENTINEL
rt[n2]=MAXINT; //SENTINEL
i=j=0;
for(int k=p;k<=r;k++)
{
if(l[i]<=rt[j])
{
a[k]=l[i];
i+=1;
}
else
{
a[k]=rt[j];
j+=1;
}
}
}
void mergesort(int a[],int p,int r)
{
int q;
if(p<r)
{
q=(p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r);
merge(a,p,q,r);
}
}
void main()
{
clrscr();
int n;
cout<<"\nEnter the no. of elements you want:";
cin>>n;
int *a=new int[n]; //dynamically initialize array
cout<<"\nEnter the elements:\n";
for(int i=0;i<n;i++)
cin>>a[i];
mergesort(a,0,n-1);
cout<<"\n\nSORTED ARRAY IS:\n";
for( i=0;i<n;i++)
cout<<a[i]<<" ";
getch();
}
By Er Gurpreet Singh,
Senior Software Engineer,
Sopra Steria India
Sunday, 2 August 2015
Merge Sort Program
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment