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

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

    In case of building the heap, we start from height, logn -1 (where logn is the height of tree of n elements). For each element present at height 'h', we go at max upto (logn -h) height down.

        So total number of traversal would be:-
        T(n) = sigma((2^(logn-h))*h) where h varies from 1 to logn
        T(n) = n((1/2)+(2/4)+(3/8)+.....+(logn/(2^logn)))
        T(n) = n*(sigma(x/(2^x))) where x varies from 1 to logn
         and according to the [sources][1]
        function in the bracket approaches to 2 at infinity.
        Hence T(n) ~ O(n)
    

提交回复
热议问题