How can building a heap be O(n) time complexity?

后端 未结 17 2681
礼貌的吻别
礼貌的吻别 2020-11-22 05:33

Can someone help explain how can building a heap be O(n) complexity?

Inserting an item into a heap is O(log n), and the insert is repeated n/2 times (t

17条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:53

    While building a heap, lets say you're taking a bottom up approach.

    1. You take each element and compare it with its children to check if the pair conforms to the heap rules. So, therefore, the leaves get included in the heap for free. That is because they have no children.
    2. Moving upwards, the worst case scenario for the node right above the leaves would be 1 comparison (At max they would be compared with just one generation of children)
    3. Moving further up, their immediate parents can at max be compared with two generations of children.
    4. Continuing in the same direction, you'll have log(n) comparisons for the root in the worst case scenario. and log(n)-1 for its immediate children, log(n)-2 for their immediate children and so on.
    5. So summing it all up, you arrive on something like log(n) + {log(n)-1}*2 + {log(n)-2}*4 + ..... + 1*2^{(logn)-1} which is nothing but O(n).

提交回复
热议问题