forked from gaurav03kr/hello-hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort.c
63 lines (56 loc) · 1011 Bytes
/
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
#include<stdio.h>
void mergeSort(int[],int,int);
void merge(int[],int,int,int);
int main()
{
int lb,ub,a[]={75,-56,-21,32,25,54,9,8};
int n = sizeof(a)/sizeof(a[0]),i;
lb = 0;ub = n - 1 ;
mergeSort(a,lb,ub);
printf("\nSorted Array : ");
for(i = 0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergeSort(int a[],int lb,int ub)
{
if(lb < ub)
{
int mid = (lb + ub)/2;
mergeSort(a,lb,mid);
mergeSort(a,mid+1,ub);
merge(a,lb,mid,ub);
}
}
void merge(int a[],int lb,int mid,int ub)
{
int i=lb,j=mid+1,k = lb;
int b [ lb + ub + 1];
while(i<=mid &&j<=ub)
{
if(a[i]<a[j])
{
b[k] = a[i];i++;k++;
}
else
{ b[k] = a[j];j++;k++;
}
}
if(i>mid)
{
while(j<=ub)
{
b[k] = a[j];
j++;k++;
}
}
else
{
while(i<=mid)
{
b[k] = a[i];i++;k++;
}
}
for(k=lb;k<=ub;k++)
a[k]=b[k];
}