aboutsummaryrefslogtreecommitdiff
path: root/heap.c
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2020-11-29 09:36:16 +0100
committerThomas Schmucker <ts@its1.de>2020-11-29 09:36:16 +0100
commitd8fa41d3f56640dcf3b59b9555d9a74d88fd48ca (patch)
tree33d182792d2133d872eaeea5be9054c93f5ebff0 /heap.c
parent321e9481ca701f32294357fa9c766564035f0f17 (diff)
downloaddata-structures-d8fa41d3f56640dcf3b59b9555d9a74d88fd48ca.tar.gz
data-structures-d8fa41d3f56640dcf3b59b9555d9a74d88fd48ca.tar.bz2
data-structures-d8fa41d3f56640dcf3b59b9555d9a74d88fd48ca.zip
min-/max-heap
Diffstat (limited to 'heap.c')
-rw-r--r--heap.c52
1 files changed, 51 insertions, 1 deletions
diff --git a/heap.c b/heap.c
index 7e0f64e..3e354c4 100644
--- a/heap.c
+++ b/heap.c
@@ -21,6 +21,8 @@ swap(T heap[], size_t i, size_t j)
21 heap[j] = temp; 21 heap[j] = temp;
22} 22}
23 23
24#if defined(MAX_HEAP)
25// MAX-HEAP Implementation
24static void 26static void
25fixup(T heap[], size_t i) 27fixup(T heap[], size_t i)
26{ 28{
@@ -59,6 +61,47 @@ fixdown(T heap[], size_t i, size_t n)
59 i = m; 61 i = m;
60 } 62 }
61} 63}
64#else
65// MIN-HEAP Implementation
66static void
67fixup(T heap[], size_t i)
68{
69 size_t p = PARENT(i);
70
71 while ( i > 0 && heap[i] < heap[p] ) {
72 swap(heap, i, p);
73
74 i = p;
75 p = PARENT(i);
76 }
77}
78
79static void
80fixdown(T heap[], size_t i, size_t n)
81{
82 for ( ;; ) {
83 const size_t l = LEFT(i);
84 const size_t r = RIGHT(i);
85 size_t m = i;
86
87 if ( l < n && heap[l] < heap[m] ) {
88 m = l;
89 }
90
91 if ( r < n && heap[r] < heap[m] ) {
92 m = r;
93 }
94
95 if ( m == i ) {
96 break;
97 }
98
99 swap(heap, m, i);
100
101 i = m;
102 }
103}
104#endif
62 105
63static void 106static void
64heapify(T heap[], size_t n) 107heapify(T heap[], size_t n)
@@ -136,7 +179,7 @@ print_heap(T heap[], size_t n)
136void 179void
137test_heapsort(void) 180test_heapsort(void)
138{ 181{
139 static const size_t N = 1001; 182 static const size_t N = 1000000;
140 T array[N]; 183 T array[N];
141 184
142 puts("fülle...."); 185 puts("fülle....");
@@ -150,10 +193,17 @@ test_heapsort(void)
150 193
151 puts("teste..."); 194 puts("teste...");
152 for ( size_t idx = 1; idx != NELEM(array); ++idx ) { 195 for ( size_t idx = 1; idx != NELEM(array); ++idx ) {
196#if defined(MAX_HEAP)
153 if ( array[idx - 1] > array[idx] ) { 197 if ( array[idx - 1] > array[idx] ) {
154 fprintf(stderr, "Fehler an Pos: %zu\n", idx); 198 fprintf(stderr, "Fehler an Pos: %zu\n", idx);
155 exit(EXIT_FAILURE); 199 exit(EXIT_FAILURE);
156 } 200 }
201#else
202 if ( array[idx - 1] < array[idx] ) {
203 fprintf(stderr, "Fehler an Pos: %zu\n", idx);
204 exit(EXIT_FAILURE);
205 }
206#endif
157 } 207 }
158 puts("ok"); 208 puts("ok");
159} 209}