0

Here is the psuedocode of the Max-Heapify algorithm :

MAX-HEAPIFY(A, i)
1. l <- Left(i)
2. r <- Right(i)
3. if l <= heap-size[A] and A[l] > A[i]
4.   largest <- l
5. else largest <- i

[...]

What's the purpose to verify that the index of the left heap is smaller equal than the size of heap A given in input ?

  • 2
    Because you are setting index in that if, if it goes beyond size or less than 0 (i.e. overflow or underflow condition) then you would end up getting exception – SMA Jan 28 '18 at 13:54
  • You wouldn't want to access elements which are not a part of heap (aka `Out of bounds`). – vishal-wadhwa Jan 28 '18 at 13:54
  • You also should make sure that `i` doesn't exceed the heap size. – Jim Mischel Jan 28 '18 at 14:22

1 Answers1

3

Here l (left) and r (right) are the index values of the left and right child, not the values itself, so to make sure the indexes (l & r) don't exceed the size of heap(Heap stored as an array) we check it against the heap size.

Rajeev Singh
  • 3,292
  • 2
  • 19
  • 30