For creating a Min heap or a Max Heap of n elements, time taken would be O(nlogn) for creating a heap. Because, every insertion takes O(logn) time and hence n elements would take O(nlogn) time
但是在很多地方都写到堆的创建可以优化到 O(n) 时间,即线性时间?但是没有明确解释如何实现?
最佳答案
最佳方法不需要logn时间来插入节点。
The optimal method starts by arbitrarily putting the elements on a binary tree, respecting the shape property (as the tree could be represented by an array). Then starting from the lowest level and moving upwards, shift the root of each subtree downward as in the deletion algorithm until the heap property is restored. More specifically if all the subtrees starting at some height
h
(measured from the bottom) have already been "heapified", the trees at heighth+1
can be heapified by sending their root down along the path of maximum valued children when building amax-heap
, or minimum valued children when building amin-heap
. This process takesO(h)
swap operations per node. In this method most of the heapification takes place in the lower levels. Since the height of the heap islogn
, the number of nodes at height ish
. Therefore, the cost of heapifying all subtrees is:h=0∑logn n/2h+1 = O(n * h=0∑lognh/2h ) which is less than
O(n * h=0∑∞h/2h )
since h / 2h converges to 2 as it is an infinite series
it is equal to
O(n)
关于algorithm - 创建最小堆或最大堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10657010/