I have implemented a min heap in C.
My heap is an array of structure. I have arranged the elements in heap according to the value of member 'length' in the structure. In my program I have to modify the 'length' of some members dynamically. After modifying this value, my heap has be reconstructed. I am finding difficulty in reconstruction part of this.
My code:
typedef struct edge{
int source;
int dest;
int length;
}edge_st;
typedef struct heap{
edge_st* edge[100];
int size;
}heap;
The code to readjust looks like below:
void modifyHeap(heap* h, int ref, int newval)
{
int i;
for(i=0; i<h->size; i++)
{
if(h->edge[i]->source == ref)
{
if(h->edge[i]->length==INT_MAX)
{
h->edge[i]->length = 0;
}
h->edge[i]->length = h->edge[i]->length+newval;
break;
}
}
heapify(h,0,h->size);
}
What I am doing is searching for the structure with a reference and changing its length value. After changing I tried doing a heapify again , but it does not work because the element I changed may not be the immediate children of root(0). If I do
heapify(h,i,h->size);
this also does not work since there may not be any children for i.
Is there any other way out of this problem?