# | Likes | Tech tags | Title | Creator | Created date |
---|---|---|---|---|---|
1 | 0 |
2022-07-31 03:21
|
|||
2 | 0 |
2022-10-31 00:50
|
An explicit implementation of the Heap data structure, commented for readability and comprehensibility. Provides \(O(\log n)\) insertion and \(O(\log n)\) deletion.
#include<vector>
#include<algorithm>
struct Heap {
// The tree relationships are index based. For node i (0-based), its children are 2*i+1 and 2*i+2
std::vector<int> _values;
void push(int value) { // Add `value` into the heap
_values.push_back(value);
int i = _values.size()-1;
// Maintain the heap property
while(i > 0 && _values[(i-1)/2] < _values[i]) {
std::swap(_values[(i-1)/2], _values[i]);
i = (i-1)/2;
}
}
int top() {
return _values[0];
}
void pop() { // Remove the highest value element
std::swap(_values[0], _values.back());
_values.pop_back();
// Restore the heap property
int i=-1, ni = 0;
while(i != ni) {
i = ni;
// Check if left child is larger than node i
if(2*i+1 < (int)_values.size() && _values[2*i+1] > _values[ni]) {
ni = 2*i+1;
}
// Check if right child is larger than node i and the left child
if(2*i+2 < (int)_values.size() && _values[2*i+2] > _values[ni]) {
ni = 2*i+2;
}
std::swap(_values[i], _values[ni]); // ni will be the index of the largest child larger than node i
}
}
};
int main() {
Heap heap;
heap.push(5);
int max_element = heap.top();
heap.pop();
}
Heap Data Structures - tutorialspoint.com
Chapter 6.1: Heaps - Introduction to Algorithms, Third Edition (Thomas H. Cormen, Charles E. Leiserson, Ronald Rivest, Clifford Stein)
classes | ||
std::vector |
en.cppreference.com | cplusplus.com |
functions | ||
std::swap |
en.cppreference.com | cplusplus.com |
std::vector::back |
en.cppreference.com | cplusplus.com |
std::vector::operator[] |
en.cppreference.com | cplusplus.com |
std::vector::pop_back |
en.cppreference.com | cplusplus.com |
std::vector::push_back |
en.cppreference.com | cplusplus.com |
std::vector::size |
en.cppreference.com | cplusplus.com |
Implement a max-heap data structure. Insert an element into it, then fetch the maximum element, then delete said maximum element.