The Binary Heap is a data structure that maintains a multiset of numbers by maintaining a complete binary tree.
Specifically, in the complete binary tree, each node stores an element of . The complete binary tree satisfies that the element in each node is less than or equal to the element in its parent.
This requires space.
Push
Push updates to in time and space.
Algorithm
-
Make a new node storing , and let it be the new rightmost leaf.
-
Maintain the order by swapping elements.
This algorithm solves the problem in time and space.
void push(int x) {
a.push_back(x);
for (int i = a.size() - 1; i > 1 && a[i >> 1] < a[i]; i >>= 1) {
std::swap(a[i >> 1], a[i]);
}
}Top
Top finds in time and space.
Algorithm
Lemma
The element in the root is .
Applying the lemma to find yields an algorithm that solves the problem in time and space.
int top() {
return a[1];
}Pop
Pop updates to in time and space.
Algorithm
-
Swap the element in the root with the element in the rightmost leaf.
-
Delete the rightmost leaf.
-
Maintain the order by swapping elements.
This algorithm solves the problem in time and space.
void pop() {
std::swap(a[1], a.back());
a.pop_back();
for (int i = 1, j; i << 1 < int(a.size()); i = j) {
j = i << 1 | ((i << 1 | 1) < int(a.size()) && a[i << 1 | 1] > a[i << 1]);
if (a[i] < a[j]) {
std::swap(a[i], a[j]);
} else {
break;
}
}
}