Lec 6 Feb 17, 2011 Section 2.5 of text (review of heap) Chapter 3
Review of heap (Sec 2.5) Heap is a data structure that supports a priority queue. Two versions (Max-heap, min-heap) Max-heap operations (can do in O(log n) time. Insert(H, x) – add x to H. Delete-max(H) – remove the max elt. from H. Other operations: increase-key, decrease-key, delete(j) – delete the key stored in index j of heap etc. Operations that take O(n) time: search(x), delete(x) etc.
Min Heap with 9 Nodes Complete binary tree with 9 nodes.
Min Heap With 9 Nodes Min-heap property: A[k] <= A[2*k] (if 2*k <= n) and A[k] <= A[2*k+1] (if 2*k+1 <= n)
Max Heap With 9 Nodes Example of a Max-heap
Heap Height Since a heap is a complete binary tree, the height of an n node heap is log 2 (n+1).
A Heap Is Efficiently Represented As An Array
Moving Up And Down A Heap Parent of node with index k is k/2 Left child of a node with index j is 2*j Right child of a node with index j is 2*j + 1
Putting An Element Into A Max Heap Place to add the new key
Putting An Element Into A Max Heap Example: New element is
Putting An Element Into A Max Heap New element is
Putting An Element Into A Max Heap New element is
Putting An Element Into A Max Heap New element is
Putting An Element Into A Max Heap New element is
Putting An Element Into A Max Heap Complete binary tree with 11 nodes
Putting An Element Into A Max Heap New element is
Putting An Element Into A Max Heap New element is
Putting An Element Into A Max Heap New element is
Complexity of insert Complexity is O(log n), where n is heap size
DeleteMax operation Max element is in the root
DeleteMax After max element is removed
DeleteMax Heap with 10 nodes. Location needs to be vacated. Find the right place to reinsert
DeleteMax Reinsert 8 into the heap.
DeleteMax Reinsert 8 into the heap
DeleteMax Reinsert 8 into the heap
DeleteMax – Another example Max element is
DeleteMax – Ex 2 After max element is removed
DeleteMax – Ex 2 Heap with 9 nodes
DeleteMax – Ex 2 Reinsert
DeleteMax – Ex 2 Reinsert
DeleteMax – Ex 2 Reinsert
Complexity of DeleteMax Complexity is O(log n). Involves working down the heap, two comparisons and 1 assignment per level. There are at most log 2 (n+1) levels. Total complexity <= 3 log 2 (n+1) = O(log n)
Delete a key at a given index Want an algorithm of complexity O(log n) Delete (2)
Delete a key at a given index To perform Delete(j): A[j] = A[size]; size--; adjust the heap at position j; How to adjust? Delete (2) similar to DeleteMax
Delete a key at a given index : Ex – Delete (6) Adjustment may require percolate_up or percolate_down
Augmenting a heap Suggest a data structure that acts like both a min-heap and max-heap. i.e., it should support all three operations in O(log n) time: Insert DeleteMin DeleteMax Any suggestion?