25 #ifndef TESSERACT_CCUTIL_GENERICHEAP_H_
26 #define TESSERACT_CCUTIL_GENERICHEAP_H_
57 template <
typename Pair>
87 const Pair&
get(
int index)
const {
96 int hole_index = heap_.
size();
102 *entry = heap_.
back();
103 hole_index = SiftUp(hole_index, *entry);
104 heap_[hole_index] = *entry;
117 int new_size = heap_.
size() - 1;
125 Pair hole_pair = heap_[new_size];
127 int hole_index = SiftDown(0, hole_pair);
128 heap_[hole_index] = hole_pair;
139 int heap_size = heap_.
size();
140 if (heap_size == 0)
return false;
145 int worst_index = heap_size - 1;
146 int end_parent = ParentNode(worst_index);
147 for (
int i = worst_index - 1; i > end_parent; --i) {
148 if (heap_[worst_index] < heap_[i])
153 *entry = heap_[worst_index];
157 Pair hole_pair = heap_[heap_size];
158 int hole_index = SiftUp(worst_index, hole_pair);
159 heap_[hole_index] = hole_pair;
175 int index = pair - &heap_[0];
176 Pair hole_pair = heap_[index];
177 index = SiftDown(index, hole_pair);
178 index = SiftUp(index, hole_pair);
179 heap_[index] = hole_pair;
186 int SiftUp(
int hole_index,
const Pair& pair) {
188 while (hole_index > 0 && pair < heap_[parent = ParentNode(hole_index)]) {
189 heap_[hole_index] = heap_[parent];
198 int SiftDown(
int hole_index,
const Pair& pair) {
199 int heap_size = heap_.
size();
201 while ((child = LeftChild(hole_index)) < heap_size) {
202 if (child + 1 < heap_size && heap_[child + 1] < heap_[child])
204 if (heap_[child] < pair) {
205 heap_[hole_index] = heap_[child];
216 int ParentNode(
int index)
const {
217 return (index + 1) / 2 - 1;
219 int LeftChild(
int index)
const {
220 return index * 2 + 1;
229 #endif // TESSERACT_CCUTIL_GENERICHEAP_H_
GenericVector< Pair > * heap()
int size_reserved() const
GenericHeap(int initial_size)
void Reshuffle(Pair *pair)
int size_reserved() const
const Pair & PeekTop() const
bool PopWorst(Pair *entry)