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

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

    There are already some great answers but I would like to add a little visual explanation

    enter image description here

    Now, take a look at the image, there are
    n/2^1 green nodes with height 0 (here 23/2 = 12)
    n/2^2 red nodes with height 1 (here 23/4 = 6)
    n/2^3 blue node with height 2 (here 23/8 = 3)
    n/2^4 purple nodes with height 3 (here 23/16 = 2)
    so there are n/2^(h+1) nodes for height h
    To find the time complexity lets count the amount of work done or max no of iterations performed by each node
    now it can be noticed that each node can perform(atmost) iterations == height of the node

    Green  = n/2^1 * 0 (no iterations since no children)  
    red    = n/2^2 * 1 (heapify will perform atmost one swap for each red node)  
    blue   = n/2^3 * 2 (heapify will perform atmost two swaps for each blue node)  
    purple = n/2^4 * 3 (heapify will perform atmost three swaps for each purple node)   
    

    so for any nodes with height h maximum work done is n/2^(h+1) * h

    Now total work done is

    ->(n/2^1 * 0) + (n/2^2 * 1)+ (n/2^3 * 2) + (n/2^4 * 3) +...+ (n/2^(h+1) * h)  
    -> n * ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) ) 
    

    now for any value of h, the sequence

    -> ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) ) 
    

    will never exceed 1
    Thus the time complexity will never exceed O(n) for building heap

提交回复
热议问题