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?
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].
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?
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 ;
}
}
Your code wouldn't heapify the array (ignoring errors like a
and boolean
)
For siftUp(), bear in mind the property parent(i) = i/2
, where i
is a node's index. Some pseudocode for inserting node into the heap (as the last node of the heap):
Algo siftUp(H[], n)
i = n
while i > 1 and H[i] < H[i/2]
swap(H[i], H[i/2])
i = i / 2
This would result in O(nlogn) as you iterate through the array, but there is a better approach with the bottom up construction with O(n).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.