-1

This is program for max heapify ,i have doubt int this algorithm,that if a already max heap is passed into this function MAX_HEAPIFY in that case largest will equal to i only and directly recursive call to MAX_HEAPIFY will execute only in that recursion will go infinitely

i am assuming that array index is starting from 1 instead of zero

   MAX_HEAPIFY(A,i,heapsize){
    l=2i;
    r=2i+1;
    if(l<=heapsize&& A[l]>A[i])
      largest=l;
    else
      largest=i;
    if(r<=heapsize&&A[r]>A[largest])
      largest=r;
    if(largest!=i)
      swap(A[i],A[largest])
    MAX_HEAPIFY(A,largest)
   }
newby
  • 189
  • 2
  • 12
  • What do you hope `l=2i;` is going to do? – fvu Nov 05 '18 at 16:39
  • @fvu i edited sir – newby Nov 05 '18 at 16:41
  • 5
    None of this is valid C, so kindly post the *real* code. Regardless, if this is an algorithm, it's wrong. There is no base-case ejection in this code; it *always* invokes recursively, so wherever you got this, it's wrong. Also, there are only *two* arguments in the recursive call, but clearly there are *three* in whatever the name represents. – WhozCraig Nov 05 '18 at 16:44
  • I actually think that you intended to write `l=2*i;` and `r=2*i+1;` – fvu Nov 05 '18 at 16:44
  • @fvu i have checked in two books it is right code' – newby Nov 05 '18 at 16:47
  • It is not. It *looks* a lot like the pseudocode one can find in several textbooks, however **all** of WhozCraig's remarks are spot on. As this question has a rather distinct homework smell I am trying to point you in the right direction without outright giving the answer... – fvu Nov 05 '18 at 17:04
  • 1
    Why in the world would you implement a binary heap in C, using index 1 as the root? It's just silly. See https://stackoverflow.com/a/49806133/56778 – Jim Mischel Nov 05 '18 at 23:18

1 Answers1

0

There may be some problem with indentation when copying this algorithm. But if you put MAX_HEAPIFY(A,largest) under this if(largest!=i) condition, then algorithm is correct. See the Algorithm below for more clarification:

MAX_HEAPIFY(A,i,heapsize){
    l=2i;
    r=2i+1;
    if(l<=heapsize&& A[l]>A[i])
      largest=l;
    else
      largest=i;
    if(r<=heapsize&&A[r]>A[largest])
      largest=r;
    if(largest!=i) {
      swap(A[i],A[largest])
      MAX_HEAPIFY(A,largest)
    }
}
nightfury1204
  • 4,364
  • 19
  • 22