C - Program to Implement Merge Sort
#include<time.h>
#include<iostream.h>
#include<conio.h>
void mergesort(int *,int,int);
void merge(int *,int,int,int);
int a[20],i,n,b[20];
void get();
void disp();
main()
{
int i;
char k='y';
do
{
clrscr();
float toc;
clock_t end,start;
start=clock();
cout<<"\n\t\t\t\tMerge Sort";
cout<<"\n\t\t\t\t----------";
get();
cout<<"\n\n\t\t\t *** Before Sorting ***\n";
disp();
mergesort(a,0,n-1);
cout<<"\n\n\t\t\t *** After Sorting ***\n";
disp();
end=clock();
toc=(end - start)/CLK_TCK;
cout<<"\n\n\tTime Complexity :: "<<toc;
cout<<"\n\n\t\t\tDo u want to continue?(y/n)";
k=getche();
}while(k=='y'||k=='Y');
}
void get()
{
int i;
cout<<"\n\n\n\tEnter the Size of Array ::";
cin>>n;
cout<<"\n\tEnter the Elements of Array ::";
for(i=0;i<n;i++)
cin>>a[i];
}
void disp()
{
int i;
cout<<"\n\tElements of Array ::";
for(i=0;i<n;i++)
{
cout<<" "<<a[i];
}
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,j);
}
}
void merge(int a[],int low,int mid ,int high)
{
int h,i,j,k;
h=low;
i=low;
j=mid+1;
while(h<=mid && j<=high)
{
if(a[h]<=a[j])
b[i]=a[h++];
else
b[i]=a[j++];
i++;
}
if( h > mid)
for(k=j;k<=high;k++)
b[i++]=a[k];
else
for(k=h;k<=mid;k++)
b[i++]=a[k];
for(k=low;k<=high;k++)
{
a[k]=b[k];
}
}
#include<iostream.h>
#include<conio.h>
void mergesort(int *,int,int);
void merge(int *,int,int,int);
int a[20],i,n,b[20];
void get();
void disp();
main()
{
int i;
char k='y';
do
{
clrscr();
float toc;
clock_t end,start;
start=clock();
cout<<"\n\t\t\t\tMerge Sort";
cout<<"\n\t\t\t\t----------";
get();
cout<<"\n\n\t\t\t *** Before Sorting ***\n";
disp();
mergesort(a,0,n-1);
cout<<"\n\n\t\t\t *** After Sorting ***\n";
disp();
end=clock();
toc=(end - start)/CLK_TCK;
cout<<"\n\n\tTime Complexity :: "<<toc;
cout<<"\n\n\t\t\tDo u want to continue?(y/n)";
k=getche();
}while(k=='y'||k=='Y');
}
void get()
{
int i;
cout<<"\n\n\n\tEnter the Size of Array ::";
cin>>n;
cout<<"\n\tEnter the Elements of Array ::";
for(i=0;i<n;i++)
cin>>a[i];
}
void disp()
{
int i;
cout<<"\n\tElements of Array ::";
for(i=0;i<n;i++)
{
cout<<" "<<a[i];
}
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,j);
}
}
void merge(int a[],int low,int mid ,int high)
{
int h,i,j,k;
h=low;
i=low;
j=mid+1;
while(h<=mid && j<=high)
{
if(a[h]<=a[j])
b[i]=a[h++];
else
b[i]=a[j++];
i++;
}
if( h > mid)
for(k=j;k<=high;k++)
b[i++]=a[k];
else
for(k=h;k<=mid;k++)
b[i++]=a[k];
for(k=low;k<=high;k++)
{
a[k]=b[k];
}
}