Docsity

Understanding Heaps: Properties, Implementation, and Applications, Slides of Data Structures and Algorithms

Partial preview of the text

Download Understanding Heaps: Properties, Implementation, and Applications and more Slides Data Structures and Algorithms in PDF only on Docsity!

Data Structures

and Algorithm Analysis

Heaps

  • A heap is a binary tree T that stores a key- element pairs at its internal nodes
  • It satisfies two properties:
    • MinHeap: key(parent) ≤ key(child)
    • [OR MaxHeap: key(parent) ≤ key(child)]
    • all levels are full, except the last one, which is left-filled

4 6

7 20 11 8

5

9 14 12

15 16 25

Heap or Not a Heap?

Heap Properties

  • A heap T storing n keys has height h = log(n + 1), which is O(log n)

4

6

7 20

11 8

5

9

14 12

15

16 25

Heap Insertion

  • Insert 6

Heap Insertion

  • Add key in next available position

Heap Insertion

Heap Insertion

  • Terminate unheap when
    • reach root
    • key child is greater than key parent

Heap Removal

  • Begin downheap

Heap Removal

Heap Removal

  • Terminate downheap when
    • reach leaf level
    • key parent is greater than key child

Building a Heap

  • build (n + 1)/2 trivial one-element heaps
  • build three-element heaps on top of them

Building a Heap

Building a Heap