1 #include "../git-compat-util.h"
4 * A merge sort implementation, simplified from the qsort implementation
5 * by Mike Haertel, which is a part of the GNU C Library.
6 * Added context pointer, safety checks and return value.
9 static void msort_with_tmp(void *b
, size_t n
, size_t s
,
10 int (*cmp
)(const void *, const void *, void *),
23 b2
= (char *)b
+ (n1
* s
);
25 msort_with_tmp(b1
, n1
, s
, cmp
, t
, ctx
);
26 msort_with_tmp(b2
, n2
, s
, cmp
, t
, ctx
);
30 while (n1
> 0 && n2
> 0) {
31 if (cmp(b1
, b2
, ctx
) <= 0) {
44 memcpy(tmp
, b1
, n1
* s
);
45 memcpy(b
, t
, (n
- n2
) * s
);
48 int git_qsort_s(void *b
, size_t n
, size_t s
,
49 int (*cmp
)(const void *, const void *, void *), void *ctx
)
51 const size_t size
= st_mult(n
, s
);
59 if (size
< sizeof(buf
)) {
60 /* The temporary array fits on the small on-stack buffer. */
61 msort_with_tmp(b
, n
, s
, cmp
, buf
, ctx
);
63 /* It's somewhat large, so malloc it. */
64 char *tmp
= xmalloc(size
);
65 msort_with_tmp(b
, n
, s
, cmp
, tmp
, ctx
);