Heap Pseudocode
function insert(heap &H,key k)
integer i;
H.n=H.n+1; // number of elements increases
H.a[n]=k; // insert element
i=H.n;
while (i>1) // root not yet reached
do
if (H.a[i]>H.a[i/2]) // heap property violated ?
then temp=H.a[i]; // yes, exchange nodes
H.a[i]=H.a[i/2];
H.a[i/2]=temp;
i=i/2; // go up in direction of root
else i=1; // exit while loop
fi
od
function delete_maximum(heap &H)
integer i;
H.a[1]=H.a[H.n]; // max now deleted
H.n=H.n-1; // number of elements decreases
i=1;
while (2*i<=H.n) // has at least a left child
do
child_left=2*i; // index of left child
child_right=2*i+1; // index of right child
if (child_right<=H.n) // does right child exist?
then // yes, then find max of both children
if (H.a[child_left]>H.a[child_right])
then child_max=child_left;
else child_max=child_right;
fi
else child_max=child_left; // no, maximum is left child
fi
if (H.a[i]<H.a[child_max]) // heap property violated?
then temp=H.a[i]; // yes, exchange nodes
H.a[i]=H.a[child_max];
H.a[child_max]=temp;
i=child_max; // go down in direction of leaf
else i=H.n+1; // exit while loop
fi
od
end
page updated Jan 12, 2021