Question: Suppose we implement the HeapSort algorithm with the following code. HeapSort divides its input into a sorted and an unsorted region, and it iteratively shrinks
Suppose we implement the HeapSort algorithm with the following code. HeapSort divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element from it and inserting it into the sorted region. Heap sort maintains the unsorted region in a heap data structure to more quickly find the largest element in each step. The HeapSort algorithm can be divided into two parts. In the first step, a max heap root node is always great or equal to leftright nodes is built out of the data see line The heap is often placed in an array with the layout of a complete binary tree. The complete binary tree maps the binary tree structure into the array indices; each array index represents a node; the index of the nodes parent, left child branch, or right child branch are simple expressions. For a zerobased array, the root node is stored at index ; In the second step starts from line a sorted array is created by repeatedly removing the largest element from the heap the root of the heap and inserting it into the array. The heap is updated after each removal to maintain the heap property. Once all objects have been removed from the heap, the result is a sorted array. public class HeapSort Given a node at index i arri Returns the rootparent node. arri Returns the left child node. arri Returns the right child node. public static void heapifyint arr, final int i final int len int j i; while true int m j; if m len int c m; if arrc arrm mc; if c len && arrc arrm mc; if mj break; int tmp arrj; arrj arrm; arrm tmp; j m; public static void sortint arr Array of size is already sorted if arrlength return; Step : Build heap for int i arr.length; i ; i heapifyarriarr.length; Step : Now sort int tmp; for int len arr.length; len; len tmp arr; arr arrlen; arrlen tmp; heapifyarrlen; tmp arr; arr arr; arr tmp; Please finish the following contracts for class HeapSort: a Precondition: the first input, ieint arr of heapify should not be null or empty. pointsb Precondition: the inputs, iei and len should be less than or equal to the size of int arr pointsc Loop Invariant of while statement line : during the process of heap building, each root is great than or equal to its left child node. pointsd Loop Invariant of while statement line : during the process of heap building, each root is great than or equal to its right child node. pointse Postcondition: after executing sortint arr the elements in arr are sorted in descending order. pointsf Postcondition: the elements in arr are the same before and after executing sortint arr points
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
