=========================================================================== CSC 263H Tutorial Outline for Week 10 Winter 2004 =========================================================================== -------- HeapSort -------- For this tutorial, you will work with MAX-heaps instead of MIN-heaps. 1. What is the ordering property for MAX-heaps? Maintaining heaps: The "percolating down" of an element that was described in lecture for the DEQUEUE operation is a very useful operation for heaps. In fact, it's so useful that it already has a name: HEAPIFY(A,i) performs this "percolating down" starting at item A[i]. 2. Describe the algorithm for HEAPIFY(A,i) and draw some examples. 3. What is the running time of HEAPIFY? Building heaps: Suppose that we already have an array A containing items with priorities, but the array is _not_ a heap. We could simply ENQUEUE each item from A into a new array B in order to form a heap. 4. What would be the complexity of doing this? There is a more efficient way to achieve the same effect: notice that every item in the second half of A corresponds to a leaf in the tree represented by A, so starting at the "middle" element (i.e., the first nonleaf node in the tree represented by A), we simply call HEAPIFY on each position of the array, working back towards position 1. 5. Write pseudo-code for this algorithm (call it BUILD-HEAP). You may make calls to HEAPIFY(A,i) for various values of i, and assume that you have access to a variable 'heapsize' that stores the number of elements in the heap. Because each item in the second half of the array is already a heap (it's a leaf), the preconditions for HEAPIFY are always verified before each call. 6. Trace BUILD-HEAP on input A = [1,5,7,6,2,9,4,8]. 7. What is the running time of BUILD-HEAP? HeapSort: Starting from an array A in some arbitrary order, we must start by building a heap from A, using the process just described. Then, set heapsize = size of A and repeatedly swap the root and the element at position heapsize (which means that the element that ends up at position heapsize is in the correct sorted position), decrement heapsize (since the last element is not part of the heap anymore), and heapify starting at the root. 8. Trace HEAPSORT on input A = [1,5,7,6,2,9,4,8] and on at least one more example of your choice, to make sure you understand how it works. 9. What is the complexity of HEAPSORT?