6-2 Analysis of -ary heaps¶
A -ary heap is like a binary heap, but (with one possible exception) nonleaf nodes have children instead of two children. In all parts of this problem, assume that the time to maintain the mapping between objects and heap elements is per operation.
a. Describe how to represent a -ary heap in an array.
b. Using -notation, express the height of a -ary heap of elements in terms of and .
c. Give an efficient implementation of EXTRACT-MAX in a -ary max-heap. Analyze its running time in terms of and .
d. Give an efficient implementation of INCREASE-KEY in a -ary max-heap. Analyze its running time in terms of and .
e. Give an efficient implementation of INSERT in a -ary max-heap. Analyze its running time in terms of and .
a¶
The array can be described by the following two fuctions to get the index of parent of -th element in the array and the -th child of -th element.
b¶
Let be the maximum numbers of elements in a -ary heap of height ? Let be the height of -ary heap of elements.
c¶
D-ARY-MAX-HEAP-EXTRACT-MAX(A)
max = A[1]
A[1] = A[n]
A.heap-size = A.heap-size - 1
D-ARY-MAX-HEAP-HEAPIFY(A,1)//Θ(d*lg(n))
return max
//
D-ARY-MAX-HEAP-HEAPIFY(A,i)
find the index j of the largest child of A[i]//Θ(d)
if j != i
exchange A[i] and A[j]
i = j
D-ARY-MAX-HEAP-HEAPIFY(A,i)//Θ(lg n) times' calling
The running time of EXTRACT-MAX .
d¶
D-ARY-MAX-HEAP-INCREASE-KEY(A,x,k)
if k < x.key
error "new key is smaller than current key"
find the index i in array A where object x occurs
while i > 1 and A[i].key < A[PARENT(i)].key
exchange A[i] and A[PARENT(i)]
update relative information
i = PARENT(i)
The number of while
loop iteration is the depth of the node which denotes x. So the running time is
e¶
D-ARY-MAX-HEAP-INSERT(A,x,n)
if A.heap-size == n
error "heap overflow"
A.heap-size = A.heap-size + 1
k = x.key
A[A.heap-size] = x
x.key = -∞
update the map between objects and array
D-ARY-MAX-HEAP-INCREASE-KEY(A,x,k)
The running time is domained by D-ARY-MAX-HEAP-INCREASE-KEY(A,x,k)
. So it is