-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsort.c
52 lines (43 loc) · 1.08 KB
/
msort.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
#include <stdlib.h>
void merge(int A[], int B[], int res[], int a, int b) {
int x = 0;
int y = 0;
for (int i = 0; i < a + b; i++) {
if (x < a) {
if (y < b) {
if (A[x] < B[y]) {
res[i] = A[x];
x++;
} else {
res[i] = B[y];
y++;
}
} else {
res[i] = A[x];
x++;
}
} else {
if (y < b) {
res[i] = B[y];
y++;
}
}
}
}
int *msort(int array[], int size) {
if (size == 1) {
int* res = malloc(sizeof(int));
if (!res) exit(1);
res[0] = array[0];
return res;
} else {
int* res = malloc(size * sizeof(int));
if (!res) exit(1);
int* A = msort(array, size / 2);
int* B = msort(array + size / 2, size / 2 + size % 2);
merge(A, B, res, size / 2, size / 2 + size % 2);
free(A);
free(B);
return res;
}
}