1 / 11

Heaps

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.).

wanda-lowe
Download Presentation

Heaps

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Heaps

  2. 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.)

  3. 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

  4. 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

  5. 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

  6. 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.

  7. Heapsort STEP 2: Remove the maximum until you’re done.

  8. Heapsort

  9. 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

  10. Priority Queue • Operations: • insert • remove highest priority item

More Related