forked from kabirthakkar/Hkfst2k21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.c
More file actions
68 lines (68 loc) · 1.18 KB
/
MergeSort.c
File metadata and controls
68 lines (68 loc) · 1.18 KB
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
#include<stdio.h>
void input(int A[],int n)
{
int i;
printf("Enter %d number of elements: ",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
}
void display(int A[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",A[i]);
}
void merge(int A[],int p,int q,int r)
{
int i,j,k;
int n1=q-p+1;
int n2=r-q;
int L[n1+1],R[n2+1];
for(i=0;i<n1;i++)
{
L[i]=A[p+i];
}
L[n1]= 99999;
for(j=0;j<n2;j++)
{
R[j]=A[q+j+1];
}
R[n2]= 99999;
i=0;
j=0;
for(k=p;k<=r;k++)
{
if(L[i]<= R[j])
{
A[k]=L[i];
i++;
}
else
{
A[k]=R[j];
j++;
}
}
}
void MergeSort(int A[],int p,int r)
{
if(p<r)
{
int q=(p+r)/2;
MergeSort(A,p,q);
MergeSort(A,q+1,r);
merge(A,p,q,r);
}
}
void main()
{
int A[20],n;
printf("\nEnter the size of the array:");
scanf("%d",&n);
input(A,n);
printf("\nArray before sorting:");
display(A,n);
MergeSort(A,0,n-1);
printf("\nArray after sorting:");
display(A,n);
}