algorithm - Deleting a node A[i] from a Max-Heap -
clrs exercise: 6.5-8
the operation heap-delete(a,i)
deletes item in node i
heap a
. give implementation of heap-delete
runs in o(lg n)
time n-element max-heap.
i wonder if algorithm wrong input a[10]={84,22,19,21,3,10,6,5,20}
(index starts 1) , a[6]=10
being deleted. replacing last node a[6]
result in violating heap property, overlooking parent value.
i wrote algorithm , wanted know if works right or going wrong ?
heap-delete(a,i) a[i]=a[a.heapsize] a.heapsize-=1 while i>1 , a[parent(i)]<a[i] swap a[i] a[parent(i)] i=parent(i);
when deleting node max heap, first thing need swap target element last element, delete last element.
now, we're faced problem of fixing max heap since moved element around. let's refer element moved x
.
there 3 cases:
x
greater parentx
less parentx
equal parent
if x
equal parent, that's easy - nothing.
if x
less parent, need max-heapify
(which i'm assuming understand how works comments), because need fix mistakes below x
.
if x
greater parent, run issue you've brought up. handling isn't tricky - need compare x
parent, , if x
greater parent, swap them. continue process until x
no longer greater parent or reach root (when x
has no parents).
with being said, pseudocode you've posted looks right me. nice work :)
Comments
Post a Comment