110 likes | 233 Views
A heap is a complete binary tree with elements filled from left to right, adhering to the heap property. In a min-heap, each node's value is less than that of its children, while a max-heap has the opposite condition. This guide explains how to insert and delete elements from a heap, ensuring it retains its properties through "bubble up" and "bubble down" techniques. Additionally, it covers heapsort and the concept of priority queues, emphasizing their operational differences compared to stacks and queues.
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