Max_Heap_Insertion (why use a sentinel??)

412 Views Asked by At

I am learning about Heaps and today I've come across this following pseudocode. So my question is: why use (-Infinity) in Max-Heap_Insert if in Heap_Increase_Key we set it to key almost right away??

    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)
1

There are 1 best solutions below

0
On

Well I have seen implementation where they do this.

heapsize++;
A[heapsize-1]=key;
Then exchange properly by comparing with parents.(if needed)

The sentinel is not something mandatory. The author took this style. You can write your own as I have said.

Example

But the code you shown is not of heap increase key. This is the correct algorithm of heap increase key.

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)

This is how the algorithm should be. Here no sentinel value is needed for sure. Also in case of insert key that is not needed.

Referrence 1. MIT Algorithm material.