I think when inserting a new node into a heap, the amount of nodes it might passes by is logN, why is it (1 + logN), where is 1 from?
Asked
Active
Viewed 121 times
0
-
4Because `log(1) = 0` but inserting into a heap with 1 element takes a comparison – harold Feb 12 '17 at 00:54
-
Thanks for your answer. I think this should be the correct answer. – user1888955 Feb 12 '17 at 02:19
1 Answers
2
This is necessary to account for the border case when the number of notes is 2n. A heap of n levels fits 2n-1 objects, so adding one more object starts the new level:
Black squares represent seven elements of a three-level heap. Red element is number eight. If your search takes you to the location of this last element, you end up with four comparisons, even though log28 is three.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
thanks for your answer But I don't understand why there are 4 comparisons. For me, it seems only 3 times even if the new added red square swims up to root (three comparisons: red line, green line and blue line, 3 times in total) – user1888955 Feb 12 '17 at 01:51
-
@user1888955 You need to compare to the root, root's child, root's grandchild, and the red node itself, to ensure that you have found the item that you are looking for. – Sergey Kalinichenko Feb 12 '17 at 01:54
-
Thank you for your quick reply :) i missed comparison on the node itself. – user1888955 Feb 12 '17 at 02:02