I am trying to implement a min heap in C but I am struggling with the sift down function.
What I have so far is :
static void sift_down(t_heap *h, int cur)
{
int min;
if (!h->nodes[cur * 2] && !h->nodes[cur * 2 + 1])
return ;
else
{
if (!(h->nodes[cur * 2] && h->nodes[cur * 2 + 1]))
{
min = (h->nodes[cur * 2]) ? cur * 2 : cur * 2 + 1;
if (h->nodes[cur]->value > h->nodes[min]->value)
{
swap(&(h->nodes[cur]), &(h->nodes[min]));
sift_down(h, min);
}
}
else
{
(min = (h->nodes[cur * 2]->value < h->nodes[cur * 2 + 1]->value) ? cur * 2 : cur * 2 + 1);
if (h->nodes[cur]->value > h->nodes[min]->value)
{
swap(&(h->nodes[cur]), &(h->nodes[min]));
sift_down(h, min);
}
}
}
}
I am sorry about the ternary conditions, I know most people dont like them, but this is for school and they force us to use ternaries.
This is currently segfaulting and I have no idea why. I tried valgrind but it didnt really help... If anyone has an idea that would be really great.