In the for loop of following code snippet about min-max heap delete-min procedure, why last=(*n)/2
? Is that because at the worse case that the x has to be inserted to the grandchild of the grandchild of ..., and for example: tree height 5: min max min max min, floor(5/2)=2, correct since at worse case only two mins following the first level. Now another one: height 4: min max min max, floor(4/2)=2, this time it doesn't work. I think maybe last=(*n)
will work, and even for(i=1;;)
will work, since it just check something that won't happen? The reason of the title is that IIRC the time complexity of min-max heap deletion is
O(log n)
but the (*n)/2
make it looks, hmm, like O(n)
.
element delete_min(element heap[], int *n) {
int i, last, k, parent;
element temp, x;
if (!(*n)) {
// checking
}
heap[0] = heap[1];
x = heap[(*n)--];
for (i=1, last=(*n)/2; i<=last; ) {
k = min_child_grandchild(i, *n);
if (x.key <= heap[k].key)
break;
heap[i] = heap[k];
if (k <= 2*i+1) {
i = k;
break;
}
parent = k/2;
if (x.key > heap[parent].key)
SWAP(heap[parent], x, temp);
i = k;
} // end for
heap[i] = x;
return heap[0];
}
source: