Merge Sort Algorithm in c/c++
Merge Sort Algorithm in c/c++
#include<stdio.h>#include<conio.h>
int a[100],b[100];
void mergesort(int low,int mid, int high)
{
int h=low,i=low,j=mid+1;
while(h<=mid && j<=high)
{
if(a[h]<a[j])
{
b[i]=a[h];
h=h+1;
}
else
{
b[i]=a[j];
j=j+1;
}
i=i+1;
}
if(h>mid)
{
for(int k=j;k<=high;k++)
{
b[i]=a[k];
i=i+1;
}
}
else
{
for(int k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(int k=low;k<=high;k++)
{
a[k]=b[k];
}
}
void merge(int l,int h)
{
int mid;
if(l<h)
{
mid=(l+h)/2;
merge(l,mid);
merge(mid+1,h);
//Combine the Solution
mergesort(l,mid,h);
}
}
void main()
{
clrscr();
int n,i;
printf("Enter How Many Elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %dth Elements ",i);
scanf("%d",&a[i]);
}
merge(0,n-1);
for(i=0;i<n;i++)
{
printf("%d,\t",a[i]);
}
getch();
}
Comments
Post a Comment