- #1
evinda
Gold Member
MHB
- 3,836
- 0
Hi! (Wave)
Given the following algorithm:
I want to write an alternative version, that uses a loop, instead of recursion.That's what I have tried:
Could you tell me if it is right? (Thinking)
Also, could you explain me why we recall the function [m] HEAPIFY [/m] only in this case:
Given the following algorithm:
Code:
HEAPIFY(A,i)
l=LEFT(i);
r=RIGHT(i)
largest=i;
if (l<=size(A) && A[l]>A[largest])
largest=l;
if (r<=size(A) && A[r]>A[largest])
largest=r;
if (largest!=i)
swap(A[i], A[largest])
HEAPIFY(A,largest)
I want to write an alternative version, that uses a loop, instead of recursion.That's what I have tried:
Code:
HEAPIFY(A,i)
l=LEFT(i);
r=RIGHT(i)
largest=i;
if (l<=size(A) && A[l]>A[largest])
largest=l;
if (r<=size(A) && A[r]>A[largest])
largest=r;
while (largest!=i)
swap(A[i], A[largest])
i=largest;
l=LEFT(i);
r=RIGHT(i)
if (l<=size(A) && A[l]>A[largest])
largest=l;
if (r<=size(A) && A[r]>A[largest])
largest=r;
Also, could you explain me why we recall the function [m] HEAPIFY [/m] only in this case:
Code:
if (largest!=i)
swap(A[i], A[largest])
HEAPIFY(A,largest)