MIN-HEAP-MINIMUM(A) if A.heap-size < 1 error “heap underflow” return A[1]
MIN-HEAP-EXTRACT-MIN(A) min = MIN-HEAP-MINIMUM(A) A[1] = A[A.heap-size] A.heap-size = A.heap-size – 1 MIN-HEAPIFY(A, 1) return min
MIN-HEAP-INCREASE-KEY(A, x, k) if k > x.key error “new key is larger than current key” x.key = k find the index i in array A where object x occurs while i > 1 and A[PARENT(i)].key > A[i].key exchange A[i] with A[PARENT(i)], updating the information that maps priority queue objects to array indices i = PARENT(i)
MIN-HEAP-INSERT(A, x, n) if A.heap-size == n error “heap overflow” A.heap-size = A.heap-size + 1 k = x.key x.key = ∞ A[A.heap-size] = x map x to index heap-size in the array MIN-HEAP-INCREASE-KEY(A, x, k)
6.5-4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
MAX-HEAP-DECREASE-KEY(A, x, k) if k > x.key error “new key is larger than current key” x.key = k find the index i in array A where object x occurs while i <= ⌊A.heap-size / 2⌋ 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[largest] largest = r if largest ≠ i exchange A[i] with A[largest], updating the information that maps priority queue objects to array indices i = largest else break
MAX-HEAP-INCREASE-KEY(A, x, k) if k < x.key error “new key is smaller than current key” x.key = k find the index i in array A where object x occurs tmp = A[i] while i > 1 and A[PARENT(i)].key < tmp.key A[i] = A[PARENT(i)] updating the information that maps priority queue objects to array indices i = PARENT(i) A[i] = tmp updating the information that maps priority queue objects to array indices
MAX-HEAP-DELETE(A, x) find the index i in array A where object x occurs A[i] = A[A.heap-size] A.heap-size = A.heap-size - 1 updating the information that maps priority queue objects to array indices MAX-HEAPIFY(A, i)
MERGE-K-SORTED-LISTS(A, k) Let H be new min-heap Let B be new array // n是全部序列长度总和。 n = 0 for i = 1 to k n = n + A[i].size() for i = 1 to k // 堆上的节点x的属性结构是(r, c, key) MIN-HEAP-INSERT(H, (i, 1, A[i, 1]), n) while H.heap-size() > 0 r, c, key = MIN-HEAP-EXTRACT-MIN(H) INSERT(B, key) if c + 1 <= A[r].size() MIN-HEAP-INSERT(H, (r, c + 1, A[r, c + 1]), n) return B