I want to implement a max binary heap in c. The header that I written:
typedef struct max_heap_t *max_heap_ptr;
max_heap_ptr max_heap_create(size_t element_size, size_t key_size, int (*key_compare)(void *a, void *b));
size_t max_heap_get_nitems(max_heap_ptr heap);
void max_heap_insert(max_heap_ptr heap, void *element_ptr, void *key_ptr);
void max_heap_max(max_heap_ptr heap, void *element_ptr);
void max_heap_extract_max(max_heap_ptr heap, void *element_ptr);
void max_heap_increase_key(max_heap_ptr heap, void *element_ptr, void *new_key);
void max_heap_free(max_heap_ptr heap);
The heap is implemented using an array.
I don't know how to implement max_heap_increase_key
. In fact given the pointer to the element, I don't know how to get the index of the element in the heap array in time O (log n). I could use a linear search, but it would take O (n) time. Do I need to use a map? I'd like to avoid this...
Any suggestions?