I am looking for a function that does Heapify but seems that there is no efficient function directly from C++ STL.
A heapify function as defined in CLRS text book will take in an element location i, assuming the left and right sub trees of i are both heaps, and make the tree rooted at i become a heap, and complexity is log(n).
Given a heap in [first, last), I would like to remove the first element, replace it with another element, and maintain the heap property. To achieve this, we only need to call heapify(first) once, traverse down the heap once, with log(n) complexity.
STL has pop_heap and push_heap functions, and it could achieve the goal by first call pop_heap and push_heap, but pop_heap maintains heap property, and push_heap also maintains heap property, this infers two traverse in the heap. Even though the overall complexity is still log(n), it is not efficient. We do not need to maintain the heap property after removing the first element.
Any good idea besides writing my own heapify function?
The standard library has no swimDown
or swimUp
functions (as described in algorithms books, anyway std::make_heap achieves heapify on a vector in linear time (details here). You can modify the element you want and then call make_heap
on the vector.
int main()
{
int myints[] = {10,20,30,5,15};
std::vector<int> v(myints,myints+5);
std::make_heap (v.begin(),v.end());
std::cout << "initial max heap : " << v.front() << '\n';
// Modify first element
v[0] = 10;
std::make_heap(v.begin(),v.end());
std::cout << "after modification max heap : " << v.front() << '\n';
}
Another solution is to
pop_heap
which will exchange the first and the last elements and reheapify (a single swimDown
)This might probably be even more efficient (if only for the number of comparisons) needed
int main()
{
int myints[] = {10,20,30,5,15};
std::vector<int> v(myints,myints+5);
std::make_heap (v.begin(),v.end());
std::cout << "initial max heap : " << v.front() << '\n';
v.push_back(10);
std::pop_heap(v.begin(), v.end()); // Takes 30 out of the heap and swims 10 down
v.pop_back(); // Drops 30
std::cout << "after modification max heap : " << v.front() << '\n';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With