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 in . The complete binary tree satisfies that the element in each node is less than or equal to the element in its parent.

This costs a space of .

Push

Push updates to in time and space.

Algorithm

  1. Make a new node that stores .

  2. 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

Since the element in each node is less than or equal to the element in its parent, the element in the root is .

Accessing the element in the root 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

  1. Swap the element in the root and the element in the last node.

  2. Delete the last node.

  3. 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;
		}
	}
}