CS2420: Lecture 20 Vladimir Kulyukin Computer Science Department Utah State University
Outline HeapSort (Chapter 7)
The Heap Property A Heap is a Complete Binary Tree. All levels are filled except possibly the last one. The Heap Property: –Minimal heap property: for every node X with parent P, the key in P is smaller than or equal to the key in X. –Maximum heap property: for every node X with parent P, the key in P is greater than or equal to the key in X.
The Heap Property P X P X The minimum heap property The maximum heap property
Packing Heaps into Arrays We can convert this heap into a one dimensional array by doing a level-order traversal on it.
Packing Heaps into Arrays Note that the index count of the array starts with 1. We can convert this heap into an array by doing a level-order traversal on it.
Packing Heaps into Arrays
Interval Nodes and Leaves Internal NodesLeaves
Leaves vs. Non-Leaves
Maintaining the Heap Property A heap is a container so items can be inserted and deleted at any time. The problem is that if we insert/delete an item, the heap property may be broken after the insertion/deletion. We need to make sure that the heap property is restored after every insertion and deletion.
Maintaining the Property: Max Heap Example Heap Property is broken.
Maintaining the Property: Example We swap 4 with the maximum of 14 and 7.
Maintaining the Property: Example We swap 4 with the maximum of 2 and 8.
Maintaining the Property: Example The heap property is now restored at every node.
RestoreHeap: Maintaining The Heap Property RestoreHeap(A, i) { int Max = 0; int LCH = LeftChild(i); int RCH = RightChild(i); If ( LCH A[i] ) { Max = LCH; } Else { Max = i; } If ( RCH A[MAX] ) { Max = RCH; } If ( Max != i ) { Swap(A[i], A[Max]); RestoreHeap(A, Max); }
RestoreHeap: Asymptotic Analysis
Building a Heap Given the dimensions of the array A, discard all the leaves. The leaf indices are [N/2 + 1, N]. Start from the Rightmost Inner (Non- Leaf) Node and go up the tree restoring the heap property at every inner node until you reach and restore the heap property at the root node.
Building a Heap
Building a Max Heap: Example There are 7 nodes in the heap; so the inner node range is [1, 3]. Thus, we start with node 3.
Building a Max Heap: Example RestoreHeap(3)
Building a Max Heap: Example RestoreHeap(2)
Building a Max Heap: Example RestoreHeap(1)
Building a Max Heap: Example RestoreHeap(3)
Building a Max Heap: Example