1

When you use a binary heap to implement a priority queue ,it is stated that the insert operation requires at most 1+lg N number of compares.(lg N = log of N,to the base 2).

Consider the below picture ,

enter image description here

Here the tree has a maximum height of 3.Even if the node T was added to the bottom most level,it will only encounter a maximum 3 nodes including the root,when T swims up.That means ,there will only be 3 compares at most.

But the statement suggests that there will be a maximum of 1+lg 11 = 1+3 = 4 compares .

How is this possible? can someone please explain?

damon
  • 8,127
  • 17
  • 69
  • 114
  • Which book/website/paper did you find that (1 + lg n) ? – George Jul 22 '13 at 15:32
  • sedgewick algorithms4 see http://algs4.cs.princeton.edu/24pq/ – damon Jul 24 '13 at 17:33
  • 1
    Consider the heap to be full, i.e., every node other than the leaves have two children. Since the height is lg N, there would be 1 + lg N nodes along any path from the root to a leaf. If you now want to insert another element, 1 + lg N comparisons would be required. – Barun Feb 27 '15 at 05:32

1 Answers1

0

Think about what would happen if you inserted node B now. There can be up to four compares, for example:

B<E? B<G? B<S? B<T?

Hope that answers your question.

PunDefeated
  • 566
  • 5
  • 18
  • The answer is almost correct except that B won't be added as a child of E, but of O. As I mentioned in my comment to the question, insertion to a full heap would lead to 1 + lg N comparisons. – Barun Feb 27 '15 at 05:34