0

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?

Vincenzo
  • 45
  • 3
  • 11
  • Isn't a max binary heap implemented as a binary tree, not an array? – PiRocks Jul 15 '20 at 07:14
  • Is the heap is an array of elements, or an array of pointers to elements? – user3386109 Jul 15 '20 at 07:16
  • @PiRocks You can implement a binary tree using an array. Check [link](https://en.wikipedia.org/wiki/Binary_heap). The implementation with arrays in this case is more efficient because it does not need to manage pointers. – Vincenzo Jul 15 '20 at 07:16
  • @user3386109 array of pointers to elements – Vincenzo Jul 15 '20 at 07:17
  • I'm aware you can implement a binary tree with an array as a backing structure, but I'm not sure why you have to use a linear search, since its still a binary tree? – PiRocks Jul 15 '20 at 07:20
  • @PiRocks I'm reading [this book](https://en.wikipedia.org/wiki/Introduction_to_Algorithms) by Thomas H. Cormen and he use arrays. Most implementations I saw on GitHub use an array (but they use simply integers as elements). However this is a binary tree (not a binary search tree). So I can't use search in log n... – Vincenzo Jul 15 '20 at 07:27
  • Idk if this helps much but all your elements are allocated in the same array, then you can derive an array index from the element_ptr with pointer arithmetic. – PiRocks Jul 15 '20 at 07:30
  • 2
    @PiRocks Memory for the element is allocated by the client. The insert operation copies the element pointer to the heap array element. So pointers to elements are not necessarily adjacent. – Vincenzo Jul 15 '20 at 08:08
  • https://cs.stackexchange.com/q/128372/755 – D.W. Jul 16 '20 at 00:38

0 Answers0