-
Notifications
You must be signed in to change notification settings - Fork 2
/
mergesort.c
84 lines (69 loc) · 1.03 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
81
82
83
84
#include<stdio.h>
#define MAX 20
void merge(int [], int, int, int);
void part(int [], int, int);
void main()
{
int a[MAX];
int n, i;
printf("Enter the number of elements to be sorted: \n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
part(a, 0, n - 1);
printf("Sorted Elements are:\n");
for(i = 0; i < n; i++)
printf("%d\n", a[i]);
}
void part(int a[], int low, int high)
{
int mid;
if(low < high)
{
mid = (low + high) / 2;
part(a, low, mid);
part(a, mid + 1, high);
merge(a, low, mid, high);
}
}
void merge(int a[], int low, int mid, int high)
{
int temp[30];
int i,j,k,m;
j = low;
m = mid + 1;
i = low;
while(j <= mid && m <= high)
{
if(a[j] <= a[m])
{
temp[i] = a[j];
j++;
}
else
{
temp[i] = a[m];
m++;
}
i++;
}
if(j > mid)
{
for(k = m; k <= high; k++)
{
temp[i] = a[k];
i++;
}
}
else
{
for(k = j; k <= mid; k++)
{
temp[i] = a[k];
i++;
}
}
for(i = low; i <= high; i++)
a[i] = temp[i];
}