LAL  7.5.0.1-b72065a
InsertionSort.c
Go to the documentation of this file.
1 /*
2 * Copyright (C) 2007 Jolien Creighton
3 * Copyright (C) 2016 Kipp Cannon
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with with program; see the file COPYING. If not, write to the
17 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 * MA 02110-1301 USA
19 */
20 
21 /*-----------------------------------------------------------------------
22  *
23  * File Name: InsertionSort.c
24  *
25  * Author: Cannon, Kipp
26  *
27  *
28  *-----------------------------------------------------------------------*/
29 
30 /* ---------- see Sort.h for doxygen documentation ---------- */
31 
32 #include <string.h>
33 #include <lal/LALStdlib.h>
34 #include <lal/Sort.h>
35 
36 
37 int XLALInsertionSort(void *base, size_t nobj, size_t size, void *params, int (*compar)(void *, const void *, const void *))
38 {
39  char *i;
40  char *end = (char *) base + nobj * size;
41  void *temp;
42 
43  /* 0 or 1 objects are already sorted. */
44  if(nobj < 2)
45  return 0;
46 
47  temp = XLALMalloc(size);
48  if(!temp)
50 
51  for(i = (char *) base + size; i < end; i += size) {
52  char *j;
53  size_t len;
54  for(j = i; j > (char *) base && compar(params, j - size, i) > 0; j -= size);
55  len = i - j;
56  if(len) {
57  memcpy(temp, i, size);
58  memmove(j + size, j, len);
59  memcpy(j, temp, size);
60  }
61  }
62 
63  XLALFree(temp);
64  return 0;
65 }
#define XLALMalloc(n)
Definition: LALMalloc.h:44
#define XLALFree(p)
Definition: LALMalloc.h:47
int XLALInsertionSort(void *base, size_t nobj, size_t size, void *params, int(*compar)(void *, const void *, const void *))
Definition: InsertionSort.c:37
#define XLAL_ERROR(...)
Macro to invoke a failure from a XLAL routine returning an integer.
Definition: XLALError.h:700
@ XLAL_ENOMEM
Memory allocation error.
Definition: XLALError.h:407