0

I can't quite figure out why my removeEntry function doesn't work. I'm trying to implement a min heap for a priority queue ADT. It uses an array of void *'s. I've verified that adding elements to the queue works. For some reason it won't heapify down correctly.

/* Removes the root element from the queue */
void *removeEntry(PQ *pq)
{   
    assert(pq != NULL);

    if(pq->count == 0)
        return NULL;

    /* idx is 0 since we're only deleting the first element */
    int idx = 0;
    int left = L_CHILD(idx), right, child;

    void * min = pq->data[0];

    pq->data[0] = pq->data[pq->count-1];

    pq->count--;

    while(left <= pq->count-1)
    {
        left = L_CHILD(idx);
        right = R_CHILD(idx);

        child = left;

        /* Check if right child exists */
        if(right <= pq->count-1)
        {
            /* Set child to the smaller child */
            if(pq->compare(pq->data[right], pq->data[left]) < 0)
                child = right;
        }

        /* If the data at idx is greater than it's child, then switch    them */
        if(pq->compare(pq->data[idx], pq->data[child]) > 0)
        {
            swap(pq->data[idx], pq->data[child]);
            idx = child;
        }
        else
            break;
        }

        return min;

}

Here are the macros I'm using to get the indices for the left and right "children"

#define L_CHILD(id) ((2*(id))+1)
#define R_CHILD(id) ((2*(id))+2)

Also here is the swap function in case anyone is curious

static void swap(void *a, void *b)
{
    void * temp;
    temp = a;
    a = b;
    b = temp;
}

Here is the add function

void addEntry(PQ *pq, void *entry)
{
    assert(pq != NULL);

    int idx = pq->count;

    if(pq->count == pq->length)
        pq = realloc(pq, sizeof(PQ *) * (pq->length * 2));

    pq->data[idx] = entry;

    /* If the last element is greater than its parents, then swap them */
    while(idx != 0 && pq->compare(pq->data[PARENT(idx)], pq->data[idx]) > 0)
    {
        swap(pq->data[PARENT(idx)], pq->data[idx]);

        idx = PARENT(idx);
    }

    pq->count++;
    return;
}
  • At least put a check for pq->count>0 in your remove code, there may be other problems and do add insert code if you can – Anil Mar 05 '19 at 01:29

1 Answers1

0
  1. Your return condition is within the scope of while loop. As a result the function is returning in the first iteration and not heapifying properly.
  2. Handle the case when left<= pq->count-1 but L_CHILD(left)>=pq->count-1.
priojeet priyom
  • 899
  • 9
  • 17