Algorithm for deletion
from a max_heap
note: deletion always deletes the root!
| 1)Remove the value from the root | |
| 2)Put the value in the last leaf in its place in the root | |
| 3)Physically delete the last leaf | |
| 4) Do the “trickle down”: p=root; while p is not a leaf and p<either child, swap with larger child |
"Element delete_max_heap(int * n)"
| Element delete_max_heap(int * n)
{ /* delete element with the highest key from the heap */ int parent, child; element item, temp; if(HEAP_EMPTY(*n)) { fprintf(stderr, “The heap is empty \n”); exit(1); } …… continued on next slide |
|
/* save value of the element with the highest key */ item = heap[0]; /* use last element in heap to adjust heap */ temp = heap[(*n)--]; parent = 0; child = 1; while (child < *n) { /* find the larger child of the current parent */ if (child < *n) && (heap[child].key < heap[child+1].key) child++; if(temp.key >= heap[child].key) break; /* move to the next lower level */ heap[parent] = heap[child]; parent = child child = 2*child + 1; } heap[parent] = temp; return item |
|
| } |