b)Sort a random array of n integers (accept the value of n from user) in ascending order by using a recursive Merge sort algorithm.
Solution:
#include<stdio.h>void merge(int *a, 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 mergesort(int *a, int low,int high)
{
int mid;
if(low!=high)
{
mid=((low+high)/2);
mergesort(a, low, mid);
mergesort(a, mid+1, high);
merge(a,low,mid,high);
}
}
void generate(int *a,int n)
{
int i;
for(i=0;i<n;i++)
a[i]=rand()%100;
}
void display(int *a,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
main()
{
int a[20],i,j,n;
printf("\n Enter how many elements:");
scanf("%d",&n);
generate(a,n);
printf("\n Elements are:\n");
display(a,n);
mergesort(a,0,n-1);
printf("\n After sorting elements are :\n");
display(a,n);
}
0 Comments:
Post a Comment