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

后端 未结 17 2752
礼貌的吻别
礼貌的吻别 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:37

    Lets suppose you have N elements in a heap. Then its height would be Log(N)

    Now you want to insert another element, then the complexity would be : Log(N), we have to compare all the way UP to the root.

    Now you are having N+1 elements & height = Log(N+1)

    Using induction technique it can be proved that the complexity of insertion would be ∑logi.

    Now using

    log a + log b = log ab

    This simplifies to : ∑logi=log(n!)

    which is actually O(NlogN)

    But

    we are doing something wrong here, as in all the case we do not reach at the top. Hence while executing most of the times we may find that, we are not going even half way up the tree. Whence, this bound can be optimized to have another tighter bound by using mathematics given in answers above.

    This realization came to me after a detail though & experimentation on Heaps.

提交回复
热议问题