110 likes | 225 Views
Heaps. What's a heap ?. a complete binary tree It has no holes; it is filled row by row, from left to right. satisfies the heap property The value at each node is smaller than that of both its children. (This is a min heap. In a max heap each node is larger than its children.).
E N D
What's a heap? • a complete binary tree • It has no holes; it isfilled row by row,from left to right. • satisfies the heap property • The value at each node is smaller than that of both its children. • (This is a min heap. In a max heap each node is larger than its children.)
Inserting into a heap 3 3 3 3 • Put the item at the end (in the first available spot) • “Bubble up” until the tree satisfies the heap property. 4 4 4 4 15 15 15 15 16 16 16 16 20 20 17 17 17 17 7 7 7 7 20 20 19 19 19 19 27 27 27 27 6 6 6
Deleting the min from a heap 4 4 • Remove the minimum. • Move the last element to the root. • “Bubble down” until the tree satisfies the heap property. 20 4 4 7 20 15 15 15 15 20 16 16 16 16 17 17 17 17 7 7 7 20 19 19 19 19 27 27 27 27 6 6 6 6
Implementing a heap 3 Use an array! parent(i) = (i-1)/2 left_child(i) = i*2+1 right_child(i) = i*2+2 4 15 left children 16 20 17 7 19 27 right children
Application 1: Sorting STEP 1: Build a max heap from the bottom up. Make left subtree a heap. Make right subtree a heap. Make the whole tree a heap.
Heapsort STEP 2: Remove the maximum until you’re done.
Application 2: Priority Queue • A new Abstract Data Type • Recall: • STACK: items are pulled out in "last in first out" order • QUEUE: items are pulled out in "first in first out" order • PRIORITY QUEUE: items are pulled out highest priority first
Priority Queue • Operations: • insert • remove highest priority item