Ejemplo n.º 1
0
element delete_max_heap(int *n)
{
    /* delete element with the highest key from heap */
    int parent, child; // variables of key
    element item, temp;
    if (HEAP_EMPTY(*n))
    {
        fprintf(stderr, "The heap is empty.\n");
        exit(EXIT_FAILURE);
    }
    /* save value of the element with the highest key */
    item = heap[1];
    temp = heap[(*n)--];
    parent = 1;
    child = 2;
    while (child <= *n)
    {
        /* find the larger child of the current paren */
        if ((child < *n) && (heap[child].key < heap[child+1].key))
            child++;
        /* move to next lower level */
        if (temp.key >= heap[child].key)
            break;
        heap[parent] = heap[child];
        parent =child;
        child *= 2;
    }
    heap[parent] = temp;
    return item;
}
Ejemplo n.º 2
0
struct heap_t *heap_max_delete (struct heap_h *h)
{
   int parent, child;
   struct heap_t *item, *temp;

   if (HEAP_EMPTY (h))
      return NULL;

   item = (h->p + 1);
   temp = (h->p + (h->cnt)--);

   parent = 1;
   child = 2;

   while (child <= h->cnt)
   {
      if ((child < h->cnt) && ((h->p + child)->key < (h->p + child + 1)->key))
         child++;
      
      if (temp->key >= (h->p + child)->key)
         break;

      memcpy (h->p + parent, h->p + child, sizeof (struct heap_t));
      parent = child;
      child *= 2;
   }

   memcpy (h->p + parent, temp, sizeof (struct heap_t));
   return item;
}