Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

All of the questions in this homework involve heap data structure and heapsort.

ID: 3739724 • Letter: A

Question

All of the questions in this homework involve heap data structure and heapsort. Assume that the heap is constructed in an array A. The size of the array is n. The elements in the array are indexed as 0,1,..., -1. Answer the following questions. 1. Write the pseudocode to find the parent, left child, and right child of node i in the heap 2. What are the minimum and maximum number of elements in a heap of height h? 3. Write down the pseudocode for Max-Heapify 4. What is the effect of calling Max-Heapify(A, i) when the element Ali is larger than its children? 5. Write down the pseudocode to build a max heap in the array A 6. Write down the pseudocode to sort (in ascending order) the elements in A using heap 7. What is the runtime of the heapsort algorithm?

Explanation / Answer

1) its left child is located at 2*i index , right child is located at 2*i+1 index , parent is located at i/2 index.

2)The range of values depends on how the height of the heap is considered. Some authors consider leaf node to be height 0, whereas others consider leaf node to be at height 1. So throughout the web, you shall see plenty of conflicting ranges. For most parts, you can consider, height as the number of edges from that node to its deepest leaf.

Assuming leaf node is at height 0, the minimum number of elements in a heap is 2^h, and the maximum number of elements in the heap is 2^(h+1) - 1

Assuming leaf node is at height 1, the minimum number of elements in a heap is 2^(h-1), and the maximum number of elements in the heap is 2^h - 1

3) MAX-HEAPIFY(A,i)

7) Heap Sort has O(nlogn) time complexities for all the cases ( best case, average case and worst case).

Let us understand the reason why. The height of a complete binary tree containing n elements is log(n)

To fully heapify an element whose subtrees are already max-heaps, we need to keep comparing the element with its left and right children and pushing it downwards until it reaches a point where both its children are smaller than it.

In the worst case scenario, we will need to move an element from the root to the leaf node making a multiple of log(n) comparisons and swaps.

During the build_max_heap stage, we do that for n/2 elements so the worst case complexity of the build_heap step is n/2*log(n) ~ nlogn.

During the sorting step, we exchange the root element with the last element and heapify the root element. For each element, this again takes logn worst time because we might have to bring the element all the way from the root to the leaf. Since we repeat this n times, the heap_sort step is also nlogn.

Also since the build_max_heap and heap_sort steps are executed one after another, the algorithmic complexity is not multiplied and it remains in the order of nlogn.