伪代码
1.
max-heapify(A,i)
//assume left and right both are max heap
//pay attention to field 'i' , remember it
l=2*i
r=2*i+1
if l<=A.heap-size and A[i]<A[l] // l must be within A's scope
else
largest=i
if r<=A.heap-size and A[largest]<A[r] // r must be within A's scope
largest=r
if(largest!=i)
swap(A[largest],A[i])
max-heapify(A,largest)
2.
build-max-heap(A)
A.heap-size=A.size
mid= |_ A.heap-size/2 _| // notice that you choose the "|_ _|"
for i=mid downto 1
max-heapify(A,i)
3.
heap-sort(A)
build-max-heap(A)
for i=A.heap-size downto 2 // downto 2 is enough, '1' don't need to exchange with itself
swap(A[i],A[1])
A.heap-size=A.heap-size-1 // this change is importance because it will affect max-heapify !
max-heapify(A,1)
/**
*following are the applications of heap in priority queue: INSERT、MAXIMUM、EXTRACT-MAX、INCREASE-KEY
**/
4.
heap-extract-max(A)
if A.heap-size<1
error "out of range"
max=A[1]
//similar with heap sort , but A[1] will be abandoned afterward , so don't swap , just '=' and '-1'
A[1]=A[A.heap-size-1]
A.heap-size=A.heap-size-1
max-heapify(A,1)
return max
5.
heap-increase-key(A,i,x)
if x<A[i]
error "x is smaller than A[i]"
A[i]=x
while i>1 and A|_i/2_|<A[i]
swap (A[i],A|_i/2_|)
i=|_i/2_| // remember to update i
6.
max-heap-insert(A,x)
A.heap-size=A.heap-size+1
A[A.heap-size]=-INF
heap-increase-key(A,A.heap-size,x)