csnip  0.1
heap.h
Go to the documentation of this file.
1 #ifndef CSNIP_HEAP_H
2 #define CSNIP_HEAP_H
3 
14 #include <assert.h>
15 #include <stddef.h>
16 
17 #include <csnip/util.h>
18 #include <csnip/preproc.h>
19 
21 #define csnip_heap_SiftUp(u, v, au_lessthan_av, swap_au_av, K, N, i) \
22  do { \
23  size_t u = (size_t)(i); \
24  assert(u < (N)); \
25  while (u > 0) { \
26  size_t v = (u - 1) / (K); \
27  if (au_lessthan_av) { \
28  swap_au_av; \
29  } \
30  u = v; \
31  } \
32  } while(0)
33 
35 #define csnip_heap_SiftDown(u, v, au_lessthan_av, swap_au_av, K, N, i) \
36  do { \
37  size_t u, v; \
38  size_t csnip_heap_i = (size_t)(i); \
39  v = csnip_heap_i * (K) + 1; \
40  while (v < (size_t)(N)) { \
41  size_t csnip_heap_nu = \
42  csnip_Min(v + (K), (size_t)(N)); \
43  u = v + 1; \
44  while (u < csnip_heap_nu) { \
45  if (au_lessthan_av) \
46  v = u; \
47  ++u; \
48  } \
49  u = csnip_heap_i; \
50  if (au_lessthan_av) \
51  break; \
52  swap_au_av; \
53  csnip_heap_i = v; \
54  v = v * (K) + 1; \
55  } \
56  } while(0)
57 
59 #define csnip_heap_Heapify(u, v, au_lessthan_av, swap_au_av, K, N) \
60  do { \
61  if((N) <= 1) \
62  break; \
63  size_t csnip_h_make_i = ((N) - 1) / (K); \
64  while(1) { \
65  csnip_heap_SiftDown(u, v, \
66  au_lessthan_av, swap_au_av, \
67  K, N, csnip_h_make_i); \
68  if (csnip_h_make_i == 0) \
69  break; \
70  --csnip_h_make_i; \
71  } \
72  } while(0)
73 
85 #define CSNIP_HEAP_DECL_FUNCS(scope, prefix, gen_args) \
86  scope void prefix ## sift_up(csnip_pp_prepend_##gen_args \
87  size_t i); \
88  scope void prefix ## sift_down(csnip_pp_prepend_##gen_args \
89  size_t i); \
90  scope void prefix ## heapify(csnip_pp_list_##gen_args);
91 
119 #define CSNIP_HEAP_DEF_FUNCS(scope, prefix, gen_args, \
120  u, v, au_lessthan_av, swap_au_av, K, N) \
121  scope void prefix ## sift_up(csnip_pp_prepend_##gen_args \
122  size_t i) \
123  { \
124  csnip_heap_SiftUp(u, v, \
125  au_lessthan_av, swap_au_av, \
126  K, N, i); \
127  } \
128  \
129  scope void prefix ## sift_down(csnip_pp_prepend_##gen_args \
130  size_t i) \
131  { \
132  csnip_heap_SiftDown(u, v, \
133  au_lessthan_av, swap_au_av, \
134  K, N, i); \
135  } \
136  \
137  scope void prefix ## heapify(csnip_pp_list_##gen_args) \
138  { \
139  csnip_heap_Heapify(u, v, \
140  au_lessthan_av, swap_au_av, \
141  K, N); \
142  }
143 
146 #endif /* CSNIP_HEAP_H */
147 
148 #if defined(CSNIP_SHORT_NAMES) && !defined(CSNIP_HEAP_HAVE_SHORT_NAMES)
149 #define heap_SiftUp csnip_heap_SiftUp
150 #define heap_SiftDown csnip_heap_SiftDown
151 #define heap_Heapify csnip_heap_Heapify
152 #define CSNIP_HEAP_HAVE_SHORT_NAMES
153 #endif /* CSNIP_SHORT_NAMES && !CSNIP_HEAP_HAVE_SHORT_NAMES */