Merge Sort :
Sort a random array of n integers (accept the value of n from user) in ascending order by using a recursive Merge sort algorithm | Merge Sort
#include<stdio.h>
int a[50],n;
int main()
{
int i;
printf("How many elements are u going to enter?: ");
scanf("%d",&n);
generate(a,n);
for(i=0;i<n;i++)
printf("%d ",a[i]);
msortdiv(0,n-1);
printf("\nOrder of Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d\t",a[i]);
}
int msortdiv(int low,int high)
{
int mid;
if(low!=high)
{
mid=((low+high)/2);
msortdiv(low,mid);
msortdiv(mid+1,high);
mergesort(low,mid,high);
}
}
int mergesort(int low,int mid,int high)
{
int t[50],i,j,k;
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]>=a[j])
t[k++]=a[j++];
else
t[k++]=a[i++];
}
while(i<=mid)
t[k++]=a[i++];
while(j<=high)
t[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=t[i];
}
void generate(int a[],int n)
{
int i;
for(i=0;i<n;i++)
a[i]=rand()%100;
}
Output :
How many elements are u going to enter?: 7
41 67 34 0 69 24 78
Order of Sorted elements: 0 24 34 41 67 69 78
Process returned 0 (0x0) execution time : 2.738 s
Press any key to continue.
0 Comments
Thanks,To visit this blog.