我正在学习堆,今天我遇到了以下伪代码。所以我的问题是:为什么在Max-Heap_Insert中使用(-Infinity),如果在Heap_Increase_Key中我们几乎立即将它设置为键?
Max_Heap_Insert(array A, int key)
1. A.heap-size = A.heap-size+1
2. A[A.heap-size-1] = -Infinity
3. Heap-Increase-Key(A, A.heap-size, key)
Heap-Increase-Key(array A, int A.heap-size, int key)
1.if key < A[i]
2. error "new key is smaller than current key"
3.A[i] = key
4.while i > 1 and A[Parent(i)] < A[i]
5. exchange A[i] with A[Parent(i)]
6. i = Parent(i)
答案 0 :(得分:0)
我已经看到他们这样做的实施。
heapsize++;
A[heapsize-1]=key;
Then exchange properly by comparing with parents.(if needed)
哨兵不是强制性的。作者采用了这种风格。你可以像我说的那样自己写。
但是您显示的代码不是堆增加密钥。这是堆增加密钥的正确算法。
Heap-Increase-Key(A, i, key)
// Input: A: an array representing a heap, i: an array index, key: a new key greater than A[i]
// Output: A still representing a heap where the key of A[i] was increased to key
// Running Time: O(log n) where n =heap-size[A]
1 if key < A[i]
2 error(“New key must be larger than current key”)
3 A[i] ← key
4 while i > 1 and A[Parent(i)] < A[i]
5 exchange A[i] and A[Parent(i)]
6 i ← Parent(i)
这就是算法应该如何。这里肯定不需要哨兵值。同样在不需要插入密钥的情况下。
<子> Referrence 1.麻省理工学院算法material. 子>