21#ifndef TESSERACT_CCUTIL_GENERICHEAP_H_
22#define TESSERACT_CCUTIL_GENERICHEAP_H_
57template <
typename Pair>
64 heap_.reserve(initial_size);
75 return heap_.size_reserved();
83 std::vector<Pair> &
heap() {
87 const Pair &
get(
int index)
const {
96 int hole_index = heap_.size();
101 heap_.push_back(*entry);
102 *entry = heap_.back();
103 hole_index = SiftUp(hole_index, *entry);
104 heap_[hole_index] = *entry;
121 int new_size = heap_.size() - 1;
125 if (entry !=
nullptr) {
131 Pair hole_pair = heap_[new_size];
132 heap_.resize(new_size);
133 int hole_index = SiftDown(0, hole_pair);
134 heap_[hole_index] = hole_pair;
136 heap_.resize(new_size);
146 if (worst_index < 0) {
150 if (entry !=
nullptr) {
151 *entry = heap_[worst_index];
153 int heap_size = heap_.size() - 1;
156 Pair hole_pair = heap_[heap_size];
157 int hole_index = SiftUp(worst_index, hole_pair);
158 heap_[hole_index] = hole_pair;
160 heap_.resize(heap_size);
166 int heap_size = heap_.size();
167 if (heap_size == 0) {
174 int worst_index = heap_size - 1;
175 int end_parent = ParentNode(worst_index);
176 for (
int i = worst_index - 1;
i > end_parent; --
i) {
177 if (heap_[worst_index] < heap_[
i]) {
194 int index = pair - &heap_[0];
195 Pair hole_pair = heap_[index];
196 index = SiftDown(index, hole_pair);
197 index = SiftUp(index, hole_pair);
198 heap_[index] = hole_pair;
205 int SiftUp(
int hole_index,
const Pair &pair) {
207 while (hole_index > 0 && pair < heap_[parent = ParentNode(hole_index)]) {
208 heap_[hole_index] = heap_[parent];
217 int SiftDown(
int hole_index,
const Pair &pair) {
218 int heap_size = heap_.size();
220 while ((
child = LeftChild(hole_index)) < heap_size) {
224 if (heap_[
child] < pair) {
225 heap_[hole_index] = heap_[
child];
236 int ParentNode(
int index)
const {
237 return (index + 1) / 2 - 1;
239 int LeftChild(
int index)
const {
240 return index * 2 + 1;
244 std::vector<Pair> heap_;
bool PopWorst(Pair *entry)
const Pair & PeekTop() const
const Pair & PeekWorst() const
void Reshuffle(Pair *pair)
int size_reserved() const
std::vector< Pair > & heap()
const Pair & get(int index) const
GenericHeap(int initial_size)