Question

The tree nodes have a natural ordering: row by row, starting at the root and moving left to right

within each row. If there are n nodes, this ordering speciﬁes their positions 1,2,...,n within the array. Moving up and down the tree is easily simulated on the array, using the fact that nodenumber j hasparentbj/2candchildren 2j and 2j + 1

(a) Consider the node at position j of the array. Show that its parent is at position bj/2c and its children are at 2j and 2j + 1 (if these numbers are ≤ n).

(b) What the corresponding indices when a complete d-ary tree is stored in an array?

Figure 4.16 shows pseudocode for a binary heap, modeled on an exposition by R.E. Tarjan.

Figure4.16

Operationsonabinaryheap. procedure insert(h,x) bubbleup(h,x,|h|+ 1)

procedure decreasekey(h,x) bubbleup(h,x,h−1(x))

function deletemin(h) if |h| = 0: return null else: x = h(1) siftdown(h,h(|h|),1) return x

function makeheap(S) h = empty array of size |S| for x ∈ S: h(|h|+ 1) = x for i = |S| downto 1: siftdown(h,h(i),i) return h

procedure bubbleup(h,x,i) (place element x in position i of h, and let it bubble up) p = di/2e while i 6= 1 and key(h(p)) > key(x): h(i) = h(p); i = p; p = di/2e h(i) = x

procedure siftdown(h,x,i) (place element x in position i of h, and let it sift down) c = minchild(h,i) while c 6= 0 and key(h(c)) < key(x): h(i) = h(c); i = c; c = minchild(h,i) h(i) = x

function minchild(h,i) (return the index of the smallest child of h(i)) if 2i > |h|: return 0 (no children) else: return argmin{key(h(j)) : 2i ≤ j ≤ min{|h|,2i + 1}}

The heap is stored as an array h, which is assumed to support two constant-time operations:

• |h|, which returns the number of elements currently in the array;

• h

−1

, which returns the position of an element within the array.

The latter can always be achieved by maintaining the values of h

−1 as an auxiliary array.

(c) Show that the makeheap procedure takes O(n) time when called on a set of n elements.

P

What is the worst-case input? (Hint: Start by showing that the running time is at most

n

i=1 log(n/i).)

(a) What needs to be changed to adapt this pseudocode to d-ary heaps?

Dasgupta Algorithms book Exercise 4.16

### Recently Asked Questions

- Write in C++, develop a class named largeIntegers such that an object of this class can store any number of digits. How could I store the digits as elements in

- Pleas can you help me answer this question: which of the following is true of a strong rule ? Choose all that apply. A. A strong rule (A->B) has the same

- Please help me answer which one of the following is an indicator of a good clustering result? A) The distances between any two clusters are large while the