12 #ifndef BINARYHEAP_HPP 13 #define BINARYHEAP_HPP 15 #include "../core/alloc_func.hpp" 18 #define BINARYHEAP_CHECK 0 22 #define CHECK_CONSISTY() this->CheckConsistency() 25 #define CHECK_CONSISTY() ; 68 this->data = MallocT<T *>(max_items + 1);
96 while (child <= this->items) {
98 if (child < this->items && *this->data[child + 1] < *this->data[child]) {
102 if (!(*this->data[child] < *item)) {
107 this->data[gap] = this->data[child];
133 if (!(*item < *this->data[parent])) {
137 this->data[gap] = this->data[parent];
145 inline void CheckConsistency()
147 for (uint child = 2; child <= this->
items; child++) {
148 uint parent = child / 2;
149 assert(!(*this->data[child] < *this->data[parent]));
172 return this->items == 0;
182 return this->items >= this->
capacity;
193 return this->data[1];
205 return this->data[1 + this->
items];
216 assert(this->capacity < UINT_MAX / 2);
219 this->data = ReallocT<T*>(this->
data, this->capacity + 1);
223 uint gap = this->
HeapifyUp(++items, new_item);
224 this->data[gap] = new_item;
238 T *first = this->
Begin();
242 T *last = this->
End();
245 if (!this->
IsEmpty()) this->data[gap] = last;
258 if (index < this->items) {
263 T *last = this->
End();
268 if (!this->
IsEmpty()) this->data[gap] = last;
270 assert(index == this->items);
287 for (T **ppI = this->data + 1, **ppLast = ppI + this->items; ppI <= ppLast; ppI++) {
289 return ppI - this->
data;
uint Length() const
Get the number of items stored in the priority queue.
T * Begin()
Get the smallest item in the binary tree.
uint HeapifyUp(uint gap, T *item)
Get position for fixing a gap (upwards).
uint capacity
Maximum number of items the heap can hold.
uint items
Number of items in the heap.
bool IsEmpty() const
Test if the priority queue is empty.
CBinaryHeapT(uint max_items)
Create a binary heap.
bool IsFull() const
Test if the priority queue is full.
uint HeapifyDown(uint gap, T *item)
Get position for fixing a gap (downwards).
void Clear()
Make the priority queue empty.
#define CHECK_CONSISTY()
Don't check for consistency.
uint FindIndex(const T &item) const
Search for an item in the priority queue.
T * Shift()
Remove and return the smallest (and also first) item from the priority queue.
Binary Heap as C++ template.
T ** data
The pointer to the heap item pointers.
void Include(T *new_item)
Insert new item into the priority queue, maintaining heap order.
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
void Remove(uint index)
Remove item at given index from the priority queue.
T * End()
Get the LAST item in the binary tree.