aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--heap.c43
1 files changed, 43 insertions, 0 deletions
diff --git a/heap.c b/heap.c
index 006ec57..ea33b16 100644
--- a/heap.c
+++ b/heap.c
@@ -1,3 +1,4 @@
1#include <assert.h>
1#include <stdbool.h> 2#include <stdbool.h>
2#include <stdio.h> 3#include <stdio.h>
3#include <stdlib.h> 4#include <stdlib.h>
@@ -21,6 +22,8 @@ swap(T heap[], size_t i, size_t j)
21 heap[j] = temp; 22 heap[j] = temp;
22} 23}
23 24
25#define MAX_HEAP 1
26
24#if defined(MAX_HEAP) 27#if defined(MAX_HEAP)
25// MAX-HEAP Implementation 28// MAX-HEAP Implementation
26static void 29static void
@@ -61,6 +64,24 @@ fixdown(T heap[], size_t i, size_t n)
61 i = m; 64 i = m;
62 } 65 }
63} 66}
67
68static bool
69is_heap(T heap[], size_t n)
70{
71 for ( size_t i = 0; i < n / 2; ++i ) {
72 const size_t l = LEFT(i);
73 const size_t r = RIGHT(i);
74
75 if ( l < n && heap[i] < heap[l] ) {
76 return false;
77 }
78 if ( r < n && heap[i] < heap[r] ) {
79 return false;
80 }
81 }
82 return true;
83}
84
64#else 85#else
65// MIN-HEAP Implementation 86// MIN-HEAP Implementation
66static void 87static void
@@ -101,6 +122,23 @@ fixdown(T heap[], size_t i, size_t n)
101 i = m; 122 i = m;
102 } 123 }
103} 124}
125
126static bool
127is_heap(T heap[], size_t n)
128{
129 for ( size_t i = 0; i < n / 2; ++i ) {
130 const size_t l = LEFT(i);
131 const size_t r = RIGHT(i);
132
133 if ( l < n && heap[i] > heap[l] ) {
134 return false;
135 }
136 if ( r < n && heap[i] > heap[r] ) {
137 return false;
138 }
139 }
140 return true;
141}
104#endif 142#endif
105 143
106static void 144static void
@@ -109,6 +147,8 @@ heapify(T heap[], size_t n)
109 for ( size_t i = n / 2; i-- > 0; ) { 147 for ( size_t i = n / 2; i-- > 0; ) {
110 fixdown(heap, i, n); 148 fixdown(heap, i, n);
111 } 149 }
150
151 assert(is_heap(heap, n));
112} 152}
113 153
114static void 154static void
@@ -239,12 +279,15 @@ main(void)
239 // Kapitel 5.10, Seite 372 ff. 279 // Kapitel 5.10, Seite 372 ff.
240 T heap[20] = { 18, 18, 16, 9, 7, 1, 9, 3, 7, 5 }; 280 T heap[20] = { 18, 18, 16, 9, 7, 1, 9, 3, 7, 5 };
241 281
282 //heapify(heap, 10);
283 assert(is_heap(heap, 10));
242 print_heap(heap, 10); 284 print_heap(heap, 10);
243 285
244 //heap[10] = 13; fixup(heap, 10); 286 //heap[10] = 13; fixup(heap, 10);
245 swap(heap, 0, 9); 287 swap(heap, 0, 9);
246 fixdown(heap, 0, 9); 288 fixdown(heap, 0, 9);
247 289
290 assert(is_heap(heap, 9));
248 print_heap(heap, 9); 291 print_heap(heap, 9);
249#endif 292#endif
250} 293}