-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergesort.c
More file actions
52 lines (40 loc) · 753 Bytes
/
mergesort.c
File metadata and controls
52 lines (40 loc) · 753 Bytes
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>
#include "lib.h"
static int *merge (int *a, int an, int *b, int bn)
{
int i, j, k;
int *c;
c = malloc(sizeof(int) * (an + bn));
for (i = j = k = 0; i < an + bn; i++) {
if ((j == an) || (k == bn))
break;
if (a[j] <= b[k]) {
c[i] = a[j];
j++;
} else {
c[i] = b[k];
k++;
}
}
if (j < an) {
for (; j < an; j++, i++)
c[i] = a[j];
} else if (k < bn) {
for (; k < bn; k++, i++)
c[i] = b[k];
} else {
printf("%s: both a and b not done!\n", __func__);
}
for (i = 0; i < an + bn; i++) {
a[i] = c[i];
}
free (c);
return a;
}
int *mergesort(int *a, int n)
{
int odd = n % 2;
if (n == 1)
return a;
return merge(mergesort(a, n/2), n/2, mergesort(a + n/2, n/2 + odd), n/2 + odd);
}