Docsity

Notes on Heaps - Object-Oriented Programming II | CMSC 132, Study notes of Computer Science

Partial preview of the text

Download Notes on Heaps - Object-Oriented Programming II | CMSC 132 and more Study notes Computer Science in PDF only on Docsity!

Heaps^ CMSC 132

Department of Computer Science

University of Maryland, College Park

Overview

Heap Properties Heap Operations Heap Implementation Heap Application – Heapsort Priority Queue

Heap & Non-heap Examples

Heaps

(^6) Non-heaps

Heap Properties

Key operations

insert (

X

getSmallest ( )

Key applications

Heapsort Priority queue

Heap Insert Example

Insert (

  1. Insert toend of tree

  2. Compare to parent,swap if parent key larger

  3. Insertcomplete

Heap Insert Example

Insert (

  1. Insert toend of tree

  2. Compare to parent,swap if parent key larger

  3. Insertcomplete

Heap GetSmallest Example

getSmallest ()

  1. Replace rootwith end of tree

  2. Compare node tochildren, if larger swapwith smallest child

  3. Repeat swap

if needed

Heap GetSmallest Example

getSmallest ()

  1. Replace rootwith end of tree

  2. Compare node tochildren, if larger swapwith smallest child

  3. Repeat swap

if needed

Heap Implementation

Observations

Compact representation Edges are implicit (no storage required) Works well for complete trees (no wasted space)

Heap Implementation

Calculating node locations

Array index

i^ starts at 0

Parent(

i) =

^

(^ i

LeftChild(

i) = 2

××××^

i^ +

RightChild(

i) = 2

××××^

i^ +

Heap Implementation

Example

LeftChild(

××××^

LeftChild(

××××^

LeftChild(

××××^

Heap Implementation

Example

RightChild(

××××^

RightChild(

××××^

Heapsort Example

Input

View heap during insert, removal

As tree As array

Heapsort – Insert Values