DAA Program2

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Program-2

Sort a given set of elements using merge sort method and determine the time required to
sort the elements. Repeat the experiment for different of values of n

#include<stdio.h>
#include<conio.h>
#include<time.h>
#define MAX 100
void sort(int a[100],int low,int high)
{
int mid;
if(high>low)
{
mid=(low+high)/2;
sort(a,low,mid);
sort(a,mid+1,high);
merge(a,low,mid,high);
}
}
int merge(int a[100],int low,int mid,int high)
{
int h,j=mid+1,i=low,b[MAX],k;
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(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
return 0;
}
void main()
{
int a[MAX],i,n;
clock_t s,e;
clrscr();
printf("enter the value of n:\t");
scanf("%d",&n);
printf("enter the element:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
//a[i]=rand()%100;
//printf("%d\t",a[i]);
}
s=clock();
delay(100);
sort(a,0,n-1);
e=clock();
printf("elements are:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n time taken=%f",(e-s)/CLK_TCK);
getch();
}

Output:

You might also like