Heapify(堆化)
Insertion Method
- 逐个插入元素到堆中,每次插入操作的时间复杂度为 O(log(n))。
- 插入n个元素的总时间复杂度为 O(nlog(n))。
Heapify Method
- 如果事先知道所有元素,可以一次性将所有元素插入到数组中,然后从最后一个非叶子节点开始向上调整,构建堆。
- 这种方法利用了堆的性质,时间复杂度为 O(n)。
Heapify Runtime Idea
How many elements are in the bottom layer of the heap?
对于一个完全二叉树(即堆),底层节点的数量大约是总节点数量的一半。具体来说,如果总节点数为 n,则底层节点数约为 n/2。原因:在一棵完全二叉树中,除了底层之外的所有层都是满的,底层的节点数最多为其上层节点数的一半。这样,底层的节点数近似为总节点数的一半。
How long does bubble down take on each of these elements?对于底层节点,下沉操作时间复杂度是 O(1)O(1)O(1)。
How many elements in layer
𝑖
of heap (if bottom layer is layer
0
)?
![](https://i-blog.csdnimg.cn/direct/e2bdde24f2a24459a63ba1310f15f71e.png)
How long does bubble down take on each of these elements?
![](https://i-blog.csdnimg.cn/direct/e3f12965e09f4544a2a63ad32c691740.png)
总结来说,虽然底层的元素数量最多,但下沉操作的时间复杂度最小;而上层的元素数量较少,但下沉操作的时间复杂度较高。总体上,这些操作的时间复杂度加总后依然为 O(n)。
![](https://i-blog.csdnimg.cn/direct/6ed4220769b74b6aafc001d53e3a5712.png)