c++performancebig-opriority-queuebinary-heap

Order Notation of pop-max in a binary heap


I need to write a pop_max function for a binary heap that removes the max element. The solution given is as below:

void pop_max() {
   assert(!m_heap.empty());
   int tmp = (size()+1)/2;
   for (int i = tmp+1; i < size(); i++) {
    if (m_heap[tmp] < m_heap[i])
    tmp = i;
   }
   m_heap[tmp] = m_heap.back();
   m_heap.pop_back();
   this->percolate_up(tmp);
}

The solution also says the number of "nodes" visited is n+log(n) where n is the total number of nodes in the heap. It then goes on to say the running time is o(n).

This makes zero sense to me though.

Their solution finds the first leaf node int tmp = (size()+1)/2; then goes through the remaining leaf nodes.

Is their solution not n/2 nodes visited and o(n/2) for running time as well? Could someone explain why this might be?

Edit: O(n/2) = O(n). But what about the number of nodes visited? I still don't quite understand how it is o(n+log(n))


Solution

  • O(n/2) is equal to O(n)

    Number of nodes visited means n for the leaf nodes and log(n) for percolate up!