Heap Supported Operation(3): Insert(这是一个从下往上的过程)
Works like ExtractMin
Add an element to the end of the heap
And fix it!
这一在插入新元素后fixing the heap的过程经常被叫做"Bubble up"(上浮), "heapify up"(堆化上移), "sift up"(筛选上移),这一过程运行时间为O(log(n)).
Heap Supported Operation(4): Delete(这是一个从下往上或者从上往下的过程)
like ExtractMin
move final element of final layer into target position
fix the heap!
How do we do this? Answer: Bubble up or Bubble down
How long does it take? Answer: O(log(n))
Heap Supported Operation(5): Update(这是一个从下往上或者从上往下的过程)
Suppose we update a node by changing its key value
Just bubble up or bubble down!
Takes time O(log(n))
More on heaps
像我们用指针构建的二叉树那样展示堆
堆通常用数组来实现!
If node is at index i, where are its children? Answer: 2i and 2i+1.
数组可以使用指数遍历树的边缘edge,具有非常迅速的运行时间。
Losing Worst-case Gurantee of Insertion无法确保在最坏情况下依然能保证操作的时间复杂度
1. If don't start with large enough array, insertions may require re-size
- double size of array 通常,重新调整数组大小的策略是将数组的大小加倍。
- lost Ω(n) operations 在最坏的情况下,这种重新调整数组大小的操作会导致插入操作失去Ω(n)的时间复杂度保证。
2. Still can get amortized 𝑂(𝑙𝑜𝑔(𝑛)) operations per insertion 尽管在最坏情况下,插入操作可能需要进行数组扩容,但通过摊还分析(amortized analysis),每次插入操作的时间复杂度仍然可以保持在 O(log(n))之内。