Line | Count | Source (jump to first uncovered line) |
1 | | #include "git-compat-util.h" |
2 | | |
3 | | /* |
4 | | * A merge sort implementation, simplified from the qsort implementation |
5 | | * by Mike Haertel, which is a part of the GNU C Library. |
6 | | */ |
7 | | |
8 | | static void msort_with_tmp(void *b, size_t n, size_t s, |
9 | | int (*cmp)(const void *, const void *), |
10 | | char *t) |
11 | 0 | { |
12 | 0 | char *tmp; |
13 | 0 | char *b1, *b2; |
14 | 0 | size_t n1, n2; |
15 | |
|
16 | 0 | if (n <= 1) |
17 | 0 | return; |
18 | | |
19 | 0 | n1 = n / 2; |
20 | 0 | n2 = n - n1; |
21 | 0 | b1 = b; |
22 | 0 | b2 = (char *)b + (n1 * s); |
23 | |
|
24 | 0 | msort_with_tmp(b1, n1, s, cmp, t); |
25 | 0 | msort_with_tmp(b2, n2, s, cmp, t); |
26 | |
|
27 | 0 | tmp = t; |
28 | |
|
29 | 0 | while (n1 > 0 && n2 > 0) { |
30 | 0 | if (cmp(b1, b2) <= 0) { |
31 | 0 | memcpy(tmp, b1, s); |
32 | 0 | tmp += s; |
33 | 0 | b1 += s; |
34 | 0 | --n1; |
35 | 0 | } else { |
36 | 0 | memcpy(tmp, b2, s); |
37 | 0 | tmp += s; |
38 | 0 | b2 += s; |
39 | 0 | --n2; |
40 | 0 | } |
41 | 0 | } |
42 | 0 | if (n1 > 0) |
43 | 0 | memcpy(tmp, b1, n1 * s); |
44 | 0 | memcpy(b, t, (n - n2) * s); |
45 | 0 | } |
46 | | |
47 | | void git_stable_qsort(void *b, size_t n, size_t s, |
48 | | int (*cmp)(const void *, const void *)) |
49 | 0 | { |
50 | 0 | const size_t size = st_mult(n, s); |
51 | 0 | char *tmp; |
52 | |
|
53 | 0 | tmp = xmalloc(size); |
54 | 0 | msort_with_tmp(b, n, s, cmp, tmp); |
55 | 0 | free(tmp); |
56 | 0 | } |