Merge Sort
Program In C++:-
// Merge Sort
#include<iostream>
using namespace std;
int a[20],b[20];
void Merge(int,int,int);
void mergesort(int l,int h)
{
if(l<h)
{
int mid=(l+h)/2;
mergesort(l,mid);
mergesort(mid+1,h);
Merge(l,mid,h);
}
}
void Merge(int l,int mid,int h)
{
int i,j,k;
i=l;
j=mid+1;
k=l;
while(i<=mid && j<=h)
{
if(a[i]<=a[j])
{
b[k]=a[i];
i++;
}
else
{
b[k]=a[j];
j++;
}
k++;
}
while(i<=mid)
{
b[k]=a[i];
i++;
k++;
}
while(j<=h)
{
b[k]=a[j];
j++;
k++;
}
for(i=l;i<=h;i++)
{
a[i]=b[i];
}
}
int main()
{
int n;
cout<<"enter size of array"<<endl;
cin>>n;
cout<<"enter elements in array"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
mergesort(0,n-1);
cout<<"Sorted array is:"<<endl;
for(int i=0;i<n;i++)
{
cout<<"\t"<<a[i];
}
}
/*
Output:-
enter size of array
5
enter elements in array
45
12
32
10
56
Sorted array is:
10 12 32 45 56
Process returned 0 (0x0) execution time : 9.470 s
Press any key to continue. */
// Merge Sort
#include<iostream>
using namespace std;
int a[20],b[20];
void Merge(int,int,int);
void mergesort(int l,int h)
{
if(l<h)
{
int mid=(l+h)/2;
mergesort(l,mid);
mergesort(mid+1,h);
Merge(l,mid,h);
}
}
void Merge(int l,int mid,int h)
{
int i,j,k;
i=l;
j=mid+1;
k=l;
while(i<=mid && j<=h)
{
if(a[i]<=a[j])
{
b[k]=a[i];
i++;
}
else
{
b[k]=a[j];
j++;
}
k++;
}
while(i<=mid)
{
b[k]=a[i];
i++;
k++;
}
while(j<=h)
{
b[k]=a[j];
j++;
k++;
}
for(i=l;i<=h;i++)
{
a[i]=b[i];
}
}
int main()
{
int n;
cout<<"enter size of array"<<endl;
cin>>n;
cout<<"enter elements in array"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
mergesort(0,n-1);
cout<<"Sorted array is:"<<endl;
for(int i=0;i<n;i++)
{
cout<<"\t"<<a[i];
}
}
/*
Output:-
enter size of array
5
enter elements in array
45
12
32
10
56
Sorted array is:
10 12 32 45 56
Process returned 0 (0x0) execution time : 9.470 s
Press any key to continue. */
Comments