-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergesort.c
69 lines (61 loc) · 998 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
63
64
65
66
67
68
69
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void merge(int *v, int in, int fn, int mid)
{
int n1, n2, i, j, k;
n1 = (mid - in)+1;
n2 = (fn - mid);
int L[n1+1], R[n2+1];
for (i = 0; i < n1; ++i)
{
L[i] = v[in + i];
}
for (i = 0; i < n2; ++i)
{
R[i] = v[mid + i + 1];
}
L[n1] = INT_MAX;
R[n2] = INT_MAX;
for (i=j=0, k=in; k <= fn; k++)
{
if(L[i] <= R[j])
{
v[k] = L[i];
i++;
}
else
{
v[k] = R[j];
j++;
}
}
}
void mergesort(int *v, int in , int fn)
{
if(in < fn)
{
int mid = in+(fn-in)/2;
mergesort(v, in , mid);
mergesort(v, mid+1, fn);
merge(v, in, fn, mid);
}
}
int main()
{
int *v = (int *) malloc(sizeof(int));
int n, i=0;
while(scanf("%d", &n) != EOF)
{
v[i] = n;
v = (int *) realloc(v, sizeof(int)*(i+2));
i++;
}
int size = i;
mergesort(v, 0, size-1);
for (i = 0; i < size; ++i)
{
(i==size-1) ? printf("%d\n", v[i]) : printf("%d ", v[i]);
}
return 0;
}