0

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:

enter image description here

Kindred
  • 1,229
  • 14
  • 41
  • Duplicated in the cross site: https://cs.stackexchange.com/q/101933/64229 As this question is more related to the CS, please remove the question from here. – OmG Dec 22 '18 at 10:45
  • @OmG: It's not duplicated, the link you provided hasn't been answered:) It doesn't solve the question. – Kindred Dec 22 '18 at 11:08
  • I mean it's duplicated in posting to the site! : ) – OmG Dec 22 '18 at 11:10
  • @OmG: It's OK, I just want to be responsive and giving feedback to people's comment. I appreciate your effort making this site better. But I want to solve my question. I prefer do thing in parallel to save time. – Kindred Dec 22 '18 at 11:12

1 Answers1

1

If you iterate linearly over a range of size n, then the loop executes O(n) times. Linearly here means that you have some loop index which is modified each time through the loop by adding a constant, typically but not necessarily 1:

for(i = 0; i < n; i += c) { /* Loop executes O(n) times */ }

But that's not what is happening here. i is not being incremented by a constant. It is being set to k, where k is the index of some child or grandchild of i. The child of i whose index is the smallest is at index 2i; the grandchild whose index is the smallest is at index 4i. (Those formula are for 1-based indices, which are common in algorithm descriptions.)

So the loop is more like this (where the constant c is usually 4 but never less than 2):

for(i = 0; i < n; i *= c) { /* Loop executes O(log n) times */ }
rici
  • 234,347
  • 28
  • 237
  • 341