forked from abhishekdoifode1/Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergerecur.cpp
82 lines (72 loc) · 1.43 KB
/
mergerecur.cpp
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
81
82
#include <stdio.h>
void merge(int list[],int low,int mid,int high)
{
int i, mi, k, lo, temp[50];
lo = low;
i = low;
mi = mid + 1;
while ((lo <= mid) && (mi <= high))
{
if (list[lo] <= list[mi])
{
temp[i] = list[lo];
lo++;
}
else
{
temp[i] = list[mi];
mi++;
}
i++;
}
if (lo > mid)
{
for (k = mi; k <= high; k++)
{
temp[i] = list[k];
i++;
}
}
else
{
for (k = lo; k <= mid; k++)
{
temp[i] = list[k];
i++;
}
}
for (k = low; k <= high; k++)
{
list[k] = temp[k];
}
}
void mergeSort(int list[],int low,int high)
{
int mid;
if(low < high)
{
mid = (low + high) / 2;
mergeSort(list, low, mid);
mergeSort(list, mid + 1, high);
merge(list, low, mid, high);
}
}
int main()
{
int i, size;
printf("Enter total number of elements:");
scanf("%d", &size);
int list[size];
printf("Enter the elements:\n");
for(i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
mergeSort(list, 0, size - 1);
printf("After merge sort:\n");
for(i = 0;i < size; i++)
{
printf("%d ",list[i]);
}
return 0;
}