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

后端 未结 17 2680
礼貌的吻别
礼貌的吻别 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:45

    Successive insertions can be described by:

    T = O(log(1) + log(2) + .. + log(n)) = O(log(n!))
    

    By starling approximation, n! =~ O(n^(n + O(1))), therefore T =~ O(nlog(n))

    Hope this helps, the optimal way O(n) is using the build heap algorithm for a given set (ordering doesn't matter).

提交回复
热议问题