The tree must be a complete tree.
the only relationship between the subtrees is that they are both greater than their parent node. There is no other relationship between them.
We will use complete binary tree to implement heaps.
push():
pop():
#include <vector>
template<typename Type>
class BinaryHeap {
private:
int current_size;
vector<Type> array;
void buildHeap();
void percolateDown(int);
public:
explicit BinaryHeap(int);
explicit BinaryHeap(const vector<Type> &);
bool isempty() const;
const Type & min() const;
void makeEmpty();
void insert(const Type &);
}
template<typename Type>
BinaryHeap<Type>::BinaryHeap(int capacity = 100)
: array(capaity +1 ), current_size{0} {
// empty
}
template<typename Type>
BinaryHeap<Type>::BinaryHeap(const vector<Type> & items)
: array(items.size() + 10 ),
current_size{items.size()} {
for (int i=0; i<items.size(); ++i)
array[i + 1] = items[i];
buildHeap();
}
template<typename Type>
bool BinaryHeap<Type>::isempty() const {
return (current_size == 0);
}
template<typename Type>
Type BinaryHeap<Type>::min() const {
if (current_size == 0)
throw UndeflowExeption;
return array[1];
}
template<typename Type>
void BinaryHeap<Type>::makeEmpty() {
current_size = 0;
}
template<typename Type>
void BinaryHeap<Type>::buildHeap() {
for (int i = current_size / 2; i > 0; --i)
percolateDown(i);
}
template<typename Type>
void BinaryHeap<Type>::percolateDown(int pos) {
int child_idx;
Type tmp = std::move(array[pos]);
for( ; pos * 2 <= current_size; pos = child_idx) {
child_idx = pos * 2;
if (child_idx != current_size &&
array[child_idx + 1] < array[child_idx] )
++ child_idx;
if (array[child_idx] < tmp)
array[pos] = std::move(child_idx);
else
break;
}
array[pos] = std::move(tmp);
}
template<typename Type>
void BinaryHeap<Type>::deleteMin() {
if (isempty()) {
throw UnderflowException;
}
array[1] = std::move( array[current_size --] );
percolateDown( 1 );
}
Multiple (m) Queues | AVL (balanced) tree | Binary Heap | |
---|---|---|---|
top | $O(m)$ | $\Theta(\ln(n))$ | $\Theta(1)$ |
push | $\Theta(1)$ | $\Theta(\ln(n))$ | $\Theta(1)$ on average |
pop | $O(m)$ | $\Theta(\ln(n))$ | $O(\ln(n))$ |
front of the tree | arbitray location | back of the array | |
---|---|---|---|
insert | $O(\ln(n))$ | $O(1)$ | $O(1)$ |
access | $O(1)$ | $O(n)$ | $O(n)$ |
delete | $O(\ln(n))$ | $O(n)$ | $O(n)$ |
In [ ]: