All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
genericheap.h
Go to the documentation of this file.
1 // Copyright 2012 Google Inc. All Rights Reserved.
2 // Author: rays@google.com (Ray Smith)
4 // File: genericheap.h
5 // Description: Template heap class.
6 // Author: Ray Smith, based on Dan Johnson's original code.
7 // Created: Wed Mar 14 08:13:00 PDT 2012
8 //
9 // (C) Copyright 2012, Google Inc.
10 // Licensed under the Apache License, Version 2.0 (the "License");
11 // you may not use this file except in compliance with the License.
12 // You may obtain a copy of the License at
13 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19 //
21 
22 #include "errcode.h"
23 #include "genericvector.h"
24 
25 #ifndef TESSERACT_CCUTIL_GENERICHEAP_H_
26 #define TESSERACT_CCUTIL_GENERICHEAP_H_
27 
28 namespace tesseract {
29 
30 // GenericHeap requires 1 template argument:
31 // Pair will normally be either KDPairInc<Key, Data> or KDPairDec<Key, Data>
32 // for some arbitrary Key and scalar, smart pointer, or non-ownership pointer
33 // Data type, according to whether a MIN heap or a MAX heap is desired,
34 // respectively. Using KDPtrPairInc<Key, Data> or KDPtrPairDec<Key, Data>,
35 // GenericHeap can also handle simple Data pointers and own them.
36 // If no additional data is required, Pair can also be a scalar, since
37 // GenericHeap doesn't look inside it except for operator<.
38 //
39 // The heap is stored as a packed binary tree in an array hosted by a
40 // GenericVector<Pair>, with the invariant that the children of each node are
41 // both NOT Pair::operator< the parent node. KDPairInc defines Pair::operator<
42 // to use Key::operator< to generate a MIN heap and KDPairDec defines
43 // Pair::operator< to use Key::operator> to generate a MAX heap by reversing
44 // all the comparisons.
45 // See http://en.wikipedia.org/wiki/Heap_(data_structure) for more detail on
46 // the basic heap implementation.
47 //
48 // Insertion and removal are both O(log n) and, unlike the STL heap, an
49 // explicit Reshuffle function allows a node to be repositioned in time O(log n)
50 // after changing its value.
51 //
52 // Accessing the element for revaluation is a more complex matter, since the
53 // index and pointer can be changed arbitrarily by heap operations.
54 // Revaluation can be done by making the Data type in the Pair derived from or
55 // contain a DoublePtr as its first data element, making it possible to convert
56 // the pointer to a Pair using KDPairInc::RecastDataPointer.
57 template <typename Pair>
58 class GenericHeap {
59  public:
61  // The initial size is only a GenericVector::reserve. It is not enforced as
62  // the size limit of the heap. Caller must implement their own enforcement.
63  explicit GenericHeap(int initial_size) {
64  heap_.reserve(initial_size);
65  }
66 
67  // Simple accessors.
68  bool empty() const {
69  return heap_.empty();
70  }
71  int size() const {
72  return heap_.size();
73  }
74  int size_reserved() const {
75  return heap_.size_reserved();
76  }
77  void clear() {
78  // Clear truncates to 0 to keep the number reserved in tact.
79  heap_.truncate(0);
80  }
81  // Provides access to the underlying vector.
82  // Caution! any changes that modify the keys will invalidate the heap!
84  return &heap_;
85  }
86  // Provides read-only access to an element of the underlying vector.
87  const Pair& get(int index) const {
88  return heap_[index];
89  }
90 
91  // Add entry to the heap, keeping the smallest item at the top, by operator<.
92  // Note that *entry is used as the source of operator=, but it is non-const
93  // to allow for a smart pointer to be contained within.
94  // Time = O(log n).
95  void Push(Pair* entry) {
96  int hole_index = heap_.size();
97  // Make a hole in the end of heap_ and sift it up to be the correct
98  // location for the new *entry. To avoid needing a default constructor
99  // for primitive types, and to allow for use of DoublePtr in the Pair
100  // somewhere, we have to incur a double copy here.
101  heap_.push_back(*entry);
102  *entry = heap_.back();
103  hole_index = SiftUp(hole_index, *entry);
104  heap_[hole_index] = *entry;
105  }
106 
107  // Get the value of the top (smallest, defined by operator< ) element.
108  const Pair& PeekTop() const {
109  return heap_[0];
110  }
111 
112  // Removes the top element of the heap. If entry is not NULL, the element
113  // is copied into *entry, otherwise it is discarded.
114  // Returns false if the heap was already empty.
115  // Time = O(log n).
116  bool Pop(Pair* entry) {
117  int new_size = heap_.size() - 1;
118  if (new_size < 0)
119  return false; // Already empty.
120  if (entry != NULL)
121  *entry = heap_[0];
122  if (new_size > 0) {
123  // Sift the hole at the start of the heap_ downwards to match the last
124  // element.
125  Pair hole_pair = heap_[new_size];
126  heap_.truncate(new_size);
127  int hole_index = SiftDown(0, hole_pair);
128  heap_[hole_index] = hole_pair;
129  } else {
130  heap_.truncate(new_size);
131  }
132  return true;
133  }
134 
135  // Removes the MAXIMUM element of the heap. (MIN from a MAX heap.) If entry is
136  // not NULL, the element is copied into *entry, otherwise it is discarded.
137  // Time = O(n). Returns false if the heap was already empty.
138  bool PopWorst(Pair* entry) {
139  int heap_size = heap_.size();
140  if (heap_size == 0) return false; // It cannot be empty!
141 
142  // Find the maximum element. Its index is guaranteed to be greater than
143  // the index of the parent of the last element, since by the heap invariant
144  // the parent must be less than or equal to the children.
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])
149  worst_index = i;
150  }
151  // Extract the worst element from the heap, leaving a hole at worst_index.
152  if (entry != NULL)
153  *entry = heap_[worst_index];
154  --heap_size;
155  if (heap_size > 0) {
156  // Sift the hole upwards to match the last element of the heap_
157  Pair hole_pair = heap_[heap_size];
158  int hole_index = SiftUp(worst_index, hole_pair);
159  heap_[hole_index] = hole_pair;
160  }
161  heap_.truncate(heap_size);
162  return true;
163  }
164 
165  // The pointed-to Pair has changed its key value, so the location of pair
166  // is reshuffled to maintain the heap invariant.
167  // Must be a valid pointer to an element of the heap_!
168  // Caution! Since GenericHeap is based on GenericVector, reallocs may occur
169  // whenever the vector is extended and elements may get shuffled by any
170  // Push or Pop operation. Therefore use this function only if Data in Pair is
171  // of type DoublePtr, derived (first) from DoublePtr, or has a DoublePtr as
172  // its first element. Reshuffles the heap to maintain the invariant.
173  // Time = O(log n).
174  void Reshuffle(Pair* 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;
180  }
181 
182  private:
183  // A hole in the heap exists at hole_index, and we want to fill it with the
184  // given pair. SiftUp sifts the hole upward to the correct position and
185  // returns the destination index without actually putting pair there.
186  int SiftUp(int hole_index, const Pair& pair) {
187  int parent;
188  while (hole_index > 0 && pair < heap_[parent = ParentNode(hole_index)]) {
189  heap_[hole_index] = heap_[parent];
190  hole_index = parent;
191  }
192  return hole_index;
193  }
194 
195  // A hole in the heap exists at hole_index, and we want to fill it with the
196  // given pair. SiftDown sifts the hole downward to the correct position and
197  // returns the destination index without actually putting pair there.
198  int SiftDown(int hole_index, const Pair& pair) {
199  int heap_size = heap_.size();
200  int child;
201  while ((child = LeftChild(hole_index)) < heap_size) {
202  if (child + 1 < heap_size && heap_[child + 1] < heap_[child])
203  ++child;
204  if (heap_[child] < pair) {
205  heap_[hole_index] = heap_[child];
206  hole_index = child;
207  } else {
208  break;
209  }
210  }
211  return hole_index;
212  }
213 
214  // Functions to navigate the tree. Unlike the original implementation, we
215  // store the root at index 0.
216  int ParentNode(int index) const {
217  return (index + 1) / 2 - 1;
218  }
219  int LeftChild(int index) const {
220  return index * 2 + 1;
221  }
222 
223  private:
224  GenericVector<Pair> heap_;
225 };
226 
227 } // namespace tesseract
228 
229 #endif // TESSERACT_CCUTIL_GENERICHEAP_H_
bool Pop(Pair *entry)
Definition: genericheap.h:116
int size() const
Definition: genericvector.h:72
void truncate(int size)
int push_back(T object)
GenericVector< Pair > * heap()
Definition: genericheap.h:83
T & back() const
int size_reserved() const
Definition: genericvector.h:75
GenericHeap(int initial_size)
Definition: genericheap.h:63
void Reshuffle(Pair *pair)
Definition: genericheap.h:174
int size_reserved() const
Definition: genericheap.h:74
void Push(Pair *entry)
Definition: genericheap.h:95
const Pair & PeekTop() const
Definition: genericheap.h:108
bool empty() const
Definition: genericheap.h:68
bool PopWorst(Pair *entry)
Definition: genericheap.h:138
bool empty() const
Definition: genericvector.h:84
void reserve(int size)
#define NULL
Definition: host.h:144