I saw in a several places that in priority_queue, the complexity of pop_heap is O(2 * log(N)), is that true? If yes, where that 2 come from? After removing first element it just needs to reconstruct heap, which would take O(log(N)).
why according to standard pop_heap may use 2logN comparisons, whereas push_heap only logN
To start with, remember heap has a structure of a binary tree, it means each node has at most two children (and obviously at most one parent).
How pop_heap
works:
How push_heap
works:
So, the main difference between two above operations is the logic of heap update (reconstruct). pop_heap
uses top to bottom logic, and push_heap
uses bottom to top logic. Both of them are of O(logN) complexity, since the whole structure is a binary tree. But pop_heap
requires more comparisons because each time we need to compare current element with both 2 children. In the same time, during push_heap
we need to compare current element only with its 1 (and only) parent.