Professional Documents
Culture Documents
Chap9 HW PriorityQueueAndHeaps
Chap9 HW PriorityQueueAndHeaps
CSCI-313
C-9.29
/**
* Moves the entry at index j higher, if necessary, to restore the heap property.
* Recursive implementation.
*/
protected void upheap(int j) {
if (j > 0) { // Base case: stop recursion if reaching the root
int p = parent(j);
if (compare(heap.get(j), heap.get(p)) < 0) { // Swap if child is smaller
than parent
swap(j, p);
upheap(p); // Recursive call on the parent's location
}
}
}
-----------------------------------------------------------------------------------
-----------------
C-9.31
-----------------------------------------------------------------------------------
-----------------
C-9.34
To compute all the entries in a heap H that have a key less than or equal to k, we
can use the following algorithm:
Create an empty list or array to store the entries with keys less than or equal to
k.
Start from the root of the heap H.
If the key of the current entry is less than or equal to k, add it to the list or
array.
Recursively traverse the left and right children of the current entry, repeating
steps 3 and 4 for each child.
Return the list or array containing the entries with keys less than or equal to k.
The algorithm visits each entry in the heap H exactly once and checks its key
against k. Therefore, the time complexity of the algorithm is proportional to the
number of entries returned.
-----------------------------------------------------------------------------------
-----------------
C-9.37
To combine two binary trees T1 and T2 into a binary tree T while maintaining the
heap-order property, we can use the following algorithm:
The time complexity of this algorithm is O(h1 + h2), where h1 and h2 are the
respective heights of T1 and T2. This is because merging the trees is done in a
depth-first manner, traversing the trees from the root to the leaves, which takes
time proportional to the heights of the trees.