0

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))

Linus
  • 115
  • 2
  • 10
  • 1
    `O(n/2)` is the same is `O(n)` if you're talking about big-O. – ChrisMM May 04 '22 at 19:04
  • @ChrisMM ah I see! What about the number of nodes visited? Their solution still seems off to me... – Linus May 04 '22 at 19:06
  • 1
    Just a guess, but assuming `percolate_up` is `log(n)` nodes visited, and `pop_max`'s for loop visits `n/2` nodes, then `O(n/2 + log(n))` is the same has `O(n + log(n))` – ChrisMM May 04 '22 at 19:08
  • @ChrisMM oh great heavens! it all makes sense now! – Linus May 04 '22 at 19:10

1 Answers1

0

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

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

Linus
  • 115
  • 2
  • 10