algorithm - 创建最小堆或最大堆

标签 algorithm time heap complexity-theory time-complexity

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 height h+1 can be heapified by sending their root down along the path of maximum valued children when building a max-heap, or minimum valued children when building a min-heap. This process takes O(h) swap operations per node. In this method most of the heapification takes place in the lower levels. Since the height of the heap is logn , the number of nodes at height is h. Therefore, the cost of heapifying all subtrees is:

h=0logn n/2h+1 = O(n * h=0lognh/2h ) which is less than

O(n * h=0h/2h )

since h / 2h converges to 2 as it is an infinite series

it is equal to O(n)

来源:http://en.wikipedia.org/wiki/Binary_heap#Building_a_heap

关于algorithm - 创建最小堆或最大堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10657010/

相关文章:

java - 我们能否以更简单的方式解决这个 socks 商人问题?

algorithm - 简化递归均值计算

ruby-on-rails - 我可以/应该如何处理 RoR 'datetime' "type"/"field"?

go - 如何在 Go 中嵌入和覆盖结构

java - 没有两个连续对象相同的随机选择序列

c - Regula-Falsi 算法?

php - 检查给定日期是否已过

linux - 如何加速 Linux 内核编译?

algorithm - 排序树与RB树和堆之间的Big-O

import - SQL Developer 不会尝试导入 .xlsx 文件,因为它太大