-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort.c
80 lines (80 loc) · 1.55 KB
/
MergeSort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<stdio.h>
#include<stdlib.h>
int count;
void mergesort(int [],int,int);
void merge(int [],int,int,int);
int main()
{
int a[1200],b[1200],c[1200],n,i,c1,c2,c3,j;
printf("ENTER THE NUMBER OF ELEMENTS\n");
scanf("%d",&n);
printf("ENTER ELEMENTS\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("SORTED ARRAY IS\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
printf("TIME COMPLEXITY ANALYSIS\n");
printf("SIZE\tASC\tDESC\tRANDOM\n");
for(i=16;i<=1024;i=i*2)
{
for(j=0;j<i;j++)
{
a[j]=j;
b[j]=i-j;
c[j]=rand()%i+1;
}
count=0;
mergesort(a,0,i-1);
c1=count;
count=0;
mergesort(b,0,i-1);
c2=count;
count=0;
mergesort(c,0,i-1);
c3=count;
printf("%d\t%d\t%d\t%d\n",i,c1,c2,c3);
}
return 0;
}
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 merge(int a[],int low,int mid,int high)
{
int b[1200],i=low,j=mid+1,k=low;
while(i<=mid && j<=high)
{
if(a[i]<a[j])
{
b[k++]=a[i++];
}
else
{
b[k++]=a[j++];
}
count++;
}
while(i<=mid)
{
b[k++]=a[i++];
count++;
}
while(j<=high)
{
b[k++]=a[j++];
count++;
}
for(k=low;k<=high;k++)
a[k]=b[k];
}