A Binary Heap maintains a multiset of numbers by maintaining a complete binary tree where each vertex contains an element in , and the element in each vertex is greater than or equal to the element in its parent, which costs a space of .
Push
Push updates to in time and space.
- Make a new vertex that contains .
- Maintain the order by swapping elements.
This algorithm solves the problem in time and space.
a.push_back(x);
for (int i = a.size() - 1; i > 1; i >>= 1) {
if (a[i >> 1] > a[i]) {
std::swap(a[i >> 1], a[i]);
}
}Top
Top finds in time and space.
Since the element in each vertex is greater than or equal to the element in its parent, it follows that the element in the root is .
Finding the element in the root yields an algorithm that solves the problem in time and space.
return a[1];Pop
Pop updates to in time and space.
- Swap the element in the root with the element in the last vertex.
- Delete the last vertex.
- Maintain the order by swapping elements.
This algorithm solves the problem in time and space.
std::swap(a[1], a.back());
a.pop_back();
for (int i = 1, j; i << 1 < int(a.size()); i = j) {
j = (i << 1 | 1) >= int(a.size()) || a[i << 1] < a[i << 1 | 1] ? i << 1 : i << 1 | 1;
if (a[i] <= a[j]) {
break;
}
std::swap(a[i], a[j]);
}