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;
}