I got this question in an exam, but I'm not sure that I understand what it wants me to do. Can you please clarify that if I did the correct thing?
Question
An integer array A is passed to the function makeHeap
. if A[0] contains n, then A[1] to A[n-1] contain numbers in arbitrary order. Write makeHeap
such that A[1] to A[n-1] contain a min-heap. Your function must create the heap by processing the elements in the order A[2] , A[3] ,... , A[n-1].
My solution
void makeHeap(int A[], int n)
{
int r = n -1 ;
for(int i = 1; i <= n/2; i++)
siftUp(a, i , r );
}
/* i- parent , r - right of the array */
void siftUp(int A[], int i , int r )
{
boolean done = false ;
int j = 2* i ;
while (j <= r && !done)
{
if(A[j] > A[j+1]) // find the smalest child
j+=1 ;
if(A[i] > A[j])
{
// code to swap A[i] and A[j]
i = j ;
j = i*2 ;
}
else done = true ;
}
}
Is this solution even remotely correct? Also, is siftUp
the correct name of the function?
Edit:
My new solution
void makeHeap(int A[], int n)
{
for(int i = 1; i <= A[0]/2; i++)
siftUp(A, i );
}
/* i- parent */
void siftUp(int A[], int i )
{
bool done = false ;
int j = 2* i ;
while (i > 1 && !done)
{
if(A[j] > A[j+1]) // find the smallest child
j+=1 ;
if(A[i] > A[j])
{
/* swap A[j] and A[i] */
int temp = A[i];
A[i] = A[j];
A[j] = temp ;
j = i ;
i = i / 2 ;
}
else done = true ;
}
}