Docsity

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

Partial preview of the text

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

CMSC 132:

Object-Oriented Programming II

Heaps & Priority Queues

Department of Computer Science

University of Maryland, College Park

Overview

Binary trees

Complete

Heaps

Insert getSmallestgetSmallest

Heap applications

Heapsort Priority queues

Complete Binary Trees

Not Allowed

Basic complete tree shape

Heaps

Two key properties

Complete binary tree Value at node

Smaller than or equal to values in subtrees

Example heapExample heap

X

≤≤≤≤

Y

X

≤≤≤≤

Z

Y

X

Z

Heap Properties

Heaps are balanced trees

Height = log

2

(n) = O(log(n))

Can find smallest element easily

Always at top of heap!Always at top of heap!

Can organize heap to find

maximum

value

Value at node larger than values in subtrees Heap can track either min or max, but not both

Heap

Key operations

Insert (

X

getSmallest ( )

Key applicationsKey applications

Heapsort Priority queue

Heap Insert Example

Insert (

  1. Insert toend of tree

  2. Compare to parent,

swap if parent key larger

  1. Insert

complete

Heap Insert Example

Insert (

  1. Insert toend of tree

  2. Compare to parent,

swap if parent key larger

  1. Insert

complete

Heap GetSmallest Example

getSmallest ()

  1. Replace root

with end of tree

  1. Compare node to

children, if larger swap

with smallest child

  1. Repeat swap

if needed

Heap GetSmallest Example

getSmallest ()

  1. Replace root

with end of tree

  1. Compare node to

children, if larger swap

with smallest child

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

××××

i

RightChild(

i

××××

i

Heap Implementation

Example

LeftChild(

××××

LeftChild(

××××

LeftChild(

××××

Heap Implementation

Example

RightChild(

××××

RightChild(

××××