I got confused while solving the following problem (questions 1–3).
Question
A d-ary heap is like a binary heap, but(with one possible exception) non-leaf nodes have d children instead of 2 children.
How would you represent a d-ary heap in an array?
What is the height of a d-ary heap of n elements in terms of n and d?
Give an efficient implementation of EXTRACT-MAX in a d-ary max-heap. Analyze its running time in terms of d and n.
Give an efficient implementation of INSERT in a d-ary max-heap. Analyze its running time in terms of d and n.
Give an efficient implementation of INCREASE-KEY(A, i, k), which flags an error if k < A[i] = k and then updates the d-ary matrix heap structure appropriately. Analyze its running time in terms of d and n.
My Solution
Give an array $A[a_1 .. a_n]$
$\qquad \begin{align} \text{root} &: a_1\\ \text{level 1} &: a_{2} \dots a_{2+d-1}\\ \text{level 2} &: a_{2+d} \dots a_{2+d+d^2-1}\\ &\vdots\\ \text{level k} &: a_{2+\sum\limits_{i=1}^{k-1}d^i} \dots a_{2+\sum\limits_{i=1}^{k}d^i-1} \end{align}$
→ My notation seems a bit sophisticated. Is there any other simpler one?
Let h denotes the height of the d-ary heap.
Suppose that the heap is a complete d-ary tree $$ 1+d+d^2+..+d^h=n\\ \dfrac{d^{h+1}-1}{d-1}=n\\ h=log_d[n{d-1}+1] - 1 $$
This is my implementation:
EXTRACT-MAX(A) 1 if A.heapsize < 1 2 error "heap underflow" 3 max = A[1] 4 A[1] = A[A.heapsize] 5 A.heap-size = A.heap-size - 1 6 MAX-HEAPIFY(A, 1) 7 return max MAX-HEAPIFY(A, i) 1 assign depthk-children to AUX[1..d] 2 for k=1 to d 3 compare A[i] with AUX[k] 4 if A[i] <= AUX[k] 5 exchange A[i] with AUX[k] 6 k = largest 7 assign AUX[1..d] back to A[depthk-children] 8 if largest != i 9 MAX-HEAPIFY(A, (2+(1+d+d^2+..+d^{k-1})+(largest-1) )
The running time of MAX-HEAPIFY:
$$T_M = d(c_8*d + (c_9+..+c_13)*d +c_14*d)$$ where $c_i$ denotes the cost of i-th line above.
EXTRACT-MAX: $$ T_E = (c_1+..+c_7) + T_M \leq C*d*h\\ = C*d*(log_d[n(d-1)+1] - 1)\\ = O(dlog_d[n(d-1)]) $$
→ Is this an efficient solution? Or there is something wrong within my solution?
h = (log [nd−1+1])− 1
Thus we above explanation for height will not hold true. h = log[nd−1+1]−1 = log[nd]-1 = log[n] Although nonetheless, the height of the tree is written asΘ(log(n)).
Note: log is always to the base d for a d-ary heap. $\endgroup$