Time complexity of heap establishment

1. top down

While inserting nodes, while sorting
the inserted data of one node and one node to the bottom of the heap, each insertion requires at most h (the existing height of the tree) adjustments, and the number of nodes in each layer is 2^h, then each The general term of the total time complexity of the layer is
k*2^k, and k is from 0 to h. h = logn (the base is 2), so the integral of k from the 0-h level (using the distribution integral, the base 2 is regarded as e) to obtain
nlogn-n = n(logn -1)
logn * n = o(nlogn ).

2. Bottom up

The nodes to be sorted have been stored in the array.
The array subscript is regarded as the node number of the corresponding tree. Starting from the highest level with non-leaf nodes, judge whether its subtrees satisfy the heap, exchange o(1) if they are not satisfied, and recursively judge their subtrees (because the root node of their subtrees after the exchange The change has occurred, and the subtree may no longer be a heap) o(hk). Then, after the nodes of one layer are judged, the upper layer is judged. Assuming that there are a total of h layers, the k-th layer has to adjust its left and right subtrees at most (h-k) times, with 2^k nodes in each layer, so the total time general term for each layer is
2^k * (hK); Integrate k from 0 to h to get n-h -1; it is o(n)

Guess you like

Origin blog.csdn.net/RunningBeef/article/details/108752281