标签:
MAX-HEAPIFY(A, i) left =left(i) right=right(i) if(left<=heap-size[A] and A[left]>A[i]) then largest=left else largest=i if(right<=heap-size[A] and A[right]>A[largest]) then largest=right if(largest!=i) then exchange(A[i], A[largest]) MAX-HEAPIFY(A, largest)
BULD-MAX-HEAP(A)
heap-size[A]=legnth(A)
for i=floor(length(A)/2) downto 1
do MAX_HEAPIFY(A, i)
HEAP-SORT(A)
BUILD-MAX-HEAP(A)
for i=length(A) downto 2
do exchange(A[1], A[i])
heap-size(A)=heap-size[A]-1
MAX-HEAPIFY(A, 1)
应用:
1.比如说给定n(n非常大)个数,求最大的k个,可以先读取k个数,建立最小堆,然后与剩下的n-k个数挨个比较堆顶元素,如果数i小于堆顶元素,则进行下一轮,如果数i大于堆顶元素,则将堆顶元素赋值为数i,然后整理最小堆(MAX-HEAPIFIY(A, 1))。
标签:
原文地址:http://www.cnblogs.com/ManofLaMancha/p/4323174.html