堆是一个数组,可以被看成一个近似的完全二叉树。 树上的每一个结点对应数组中的一个元素
A[1...A.heap-size]
PARENT(i) return Li/2j
LEFT 2i
RIGHT 2i + 1
最大堆的性质 A[PARENT(i)] >= A[i]
最小堆的性子 A[PARENT(i)] <= A[i]
MAX-HEAPIFY o(lgn) 维护最大堆
BUILD-MAX-HEAP 线性时间复杂度
HEAPSORT o(n*lgn)
MAX-HEAP-INSERT, HEAP-EXPACT-MAX, HEAP-INCREASE-KEY, HEAP-MAXIMUM
MAX-HEAPIFY(i)
l = LEFT(i)
r = RIGHT(i)
if l <= A.heap-size and A[l] > A[i]
largest = l
else largest = i
if r <= A.heap-size and A[r] > A[i]
largeset = r
if largest != i
exchange A[i] with A[largest]
MAX-HEAPIFY(largest)
建堆
BUILD-MAX-HEAP(A)
A.heap-size = A.length
for i = LA.length/2J downto 1MAX-HEAPIFY(A, i)
堆排序算法
HEAPSORT(A)
BUILD-MAX-HEAP(A)
for i = A.length donwto 2
exchange A[1] with A[i]
A.heap-size = A.heap-size -1
MAX-HEAPIFY(A,1)
利用BUILD-MAX-HEAP(A)将输入数组A[1...A.length]建成最大堆 因为数组最大元素总在根A[1] , 通过它与A[n] 进行交换,我们可以让该元素放到正确位置。如果我们从堆中去掉n 剩余节点中
根的孩子仍然是最大堆,而新的根节点可能违背最大堆的性质。为了维护最大堆的性子,我们调用MAX-HEPIFY(A,1)
优先队列
INSERT(S, x)
MAXIMUM(S)
EXTRACT-MAX(S)
INCREASE-KEY(S, x, k)
用堆来实现优先队列,需要在堆中的每个元素里存储对对象的句柄
HEAP-MAXIMUM
return A[1]
HEAP-EXTRACT-MAX(S)
if A.heap-size < 1
error "heap underflow"
max = A[1]
A[1] = A[A.heap-size]
A.heap-size = A.heap-size - 1
MAX-HEAPIFY(A,1)
return max
HEAP-INCREASE-KEY(A, i, key)
if key < A[i]
error "new key is smaller than current key"
A[i] = key
while i > 1 and A[PARENT(i)] < A[i]
exchange A[i] with A[PARENT(i)]
i = PARENT(i)
MAX-HEAP-INSERT(A, key)
A.heap-size = A.heap-size + 1
A[A.heap-size] = -OO
HEAP-INCREASE-KEY(A, A.heap-size, key)