Loading [MathJax]/extensions/TeX/AMSmath.js
LAL 7.7.0.1-5e288d3
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
MergeSort.c
Go to the documentation of this file.
1#include <stddef.h>
2#include <sys/types.h>
3#include <string.h>
4#include <lal/LALStdlib.h>
5#include <lal/Sort.h>
6
7static void msort(void *base, size_t nobj, size_t size, void *params, int (*compar)(void *, const void *, const void *), void *work)
8{
9 if (nobj > 1) {
10 typedef char type[size];
11 size_t n1 = nobj >> 1;
12 size_t n2 = nobj - n1;
13 type *a1 = (type *)base;
14 type *a2 = (type *)base + n1;
15 type *tmp = (type *)work;
16
17 msort(a1, n1, size, params, compar, work);
18 msort(a2, n2, size, params, compar, work);
19
20 while (n1 > 0 && n2 > 0) {
21 if (compar(params, a1, a2) > 0) {
22 memcpy(tmp++, a2++, size);
23 --n2;
24 } else {
25 memcpy(tmp++, a1++, size);
26 --n1;
27 }
28 }
29 if (n1 > 0)
30 memcpy(tmp, a1, n1 * size);
31 memcpy(base, work, (nobj - n2) * size);
32 }
33 return;
34}
35
36int XLALMergeSort(void *base, size_t nobj, size_t size, void *params, int (*compar)(void *, const void *, const void *))
37{
38 void *work;
39 if (nobj < 2) /* 0 or 1 objects are already sorted */
40 return 0;
42 XLAL_CHECK(compar, XLAL_EFAULT);
43 XLAL_CHECK((ssize_t)size > 0, XLAL_EINVAL);
44 work = LALMalloc(nobj * size);
46 msort(base, nobj, size, params, compar, work);
47 LALFree(work);
48 return 0;
49}
#define LALMalloc(n)
Definition: LALMalloc.h:93
#define LALFree(p)
Definition: LALMalloc.h:96
static void msort(void *base, size_t nobj, size_t size, void *params, int(*compar)(void *, const void *, const void *), void *work)
Definition: MergeSort.c:7
int XLALMergeSort(void *base, size_t nobj, size_t size, void *params, int(*compar)(void *, const void *, const void *))
Definition: MergeSort.c:36
#define XLAL_CHECK(assertion,...)
Macro to test an assertion and invoke a failure if it is not true in a function that returns an integ...
Definition: XLALError.h:810
@ XLAL_ENOMEM
Memory allocation error.
Definition: XLALError.h:407
@ XLAL_EFAULT
Invalid pointer.
Definition: XLALError.h:408
@ XLAL_EINVAL
Invalid argument.
Definition: XLALError.h:409