6-2 Analysis of -ary heaps
A -ary heap is like a binary heap, but (with one possible exception) non-leaf nodes have children instead of children.
a. How would you represent a -ary heap in an array?
b. What is the height of a -ary heap of elements in terms of and ?
c. Give an efficient implementation of in a -ary max-heap. Analyze its running time in terms of and .
d. Give an efficient implementation of in a -ary max-heap. Analyze its running time in terms of and .
e. Give an efficient implementation of , which flags an error if , but otherwise sets and then updates the -ary max-heap structure appropriately. Analyze its running time in terms of and .
a. We can use those two following functions to retrieve parent of -th element and -th child of -th element.
d-ARY-PARENT(i)
return floor((i - 2) / d + 1)
d-ARY-CHILD(i, j)
return d(i − 1) + j + 1
Obviously . You can verify those functions checking that
Also easy to see is that binary heap is special type of -ary heap where , if you substitute with , then you will see that they match functions , and mentioned in book.
b. Since each node has children, the height of a -ary heap with nodes is .
c. consists of constant time operations, followed by a call to .
The number of times this recursively calls itself is bounded by the height of the -ary heap, so the running time is .
d-ARY-HEAP-EXTRACT-MAX(A)
if A.heap-size < 1
error "heap under flow"
max = A[1]
A[1] = A[A.heap-size]
A.heap-size = A.heap-size - 1
d-ARY-MAX-HEAPIFY(A, 1)
return max
d-ARY-MAX-HEAPIFY(A, i)
largest = i
for k = 1 to d
if d-ARY-CHILD(k, i) ≤ A.heap-size and A[d-ARY-CHILD(k, i)] > A[i]
if A[d-ARY-CHILD(k, i)] > largest
largest = A[d-ARY-CHILD(k, i)]
if largest != i
exchange A[i] with A[largest]
d-ARY-MAX-HEAPIFY(A, largest)
d. The runtime is since the while loop runs at most as many times as the height of the -ary array.
d-ARY-MAX-HEAP-INSERT(A, key)
A.heap-size = A.heap-size + 1
A[A.heap-size] = key
i = A.heap-size
while i > 1 and A[d-ARY-PARENT(i) < A[i]]
exchange A[i] with A[d-ARY-PARENT(i)]
i = d-ARY-PARENT(i)
e. The runtime is since the while loop runs at most as many times as the height of the -ary array.
d-ARY-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[d-ARY-PARENT(i) < A[i]]
exchange A[i] with A[d-ARY-PARENT(i)]
i = d-ARY-PARENT(i)