Docsity

Object-Oriented Programming II: Heaps and Priority Queues - Prof. Nelson Padua-Perez, Study notes of Computer Science

Partial preview of the text

Download Object-Oriented Programming II: Heaps and Priority Queues - Prof. Nelson Padua-Perez 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

Full, Perfect, Complete

Heaps

Insert getSmallest

Heap applications

Heapsort Priority queues

Perfect Binary Tree

A^

full

binary tree where

All leaves at level

h for tree of height

h

h = 2

h = 4

h = 3

h = 1

Complete Binary Trees

An binary tree (height h) where

Perfect tree to level

h-

Leaves at level

h

are as far

left

as possible

h = 2

h = 3

h = 1

Heaps

Two key properties

Complete binary tree Value at node

Smaller than or equal to values in subtrees

Example heap

X^

≤≤≤≤^

Y

X^

≤≤≤≤^

Z

Y

X

Z

Heap & Non-heap Examples

Heaps

(^6) Non-heaps

Heap

Key operations

Insert (

X

getSmallest ( )

Key applications

Heapsort Priority queue

Heap Operations – Insert( X )

Algorithm 1.^

Add X to end of tree

2.^

While (X < parent)

Swap X with parent

// X bubbles up tree

Complexity

of swaps proportional to height of tree O( log(n) )

Heap Insert Example

Insert (

  1. Insert toend of tree

  2. Compare to parent,swap if parent key larger

  3. Insertcomplete

Heap Operation – getSmallest()

Algorithm 1.^

Get smallest node at root

2.^

Replace root with X at end of tree

3.^

While ( X > child )

Swap X with smallest child

// X drops down tree

4.^

Return smallest node

Complexity

swaps proportional to height of tree O( log(n) )

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

Can implement heap as array

Store nodes in array elements Assign location (index) for elements using formula

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

Parent(

^

(^1

^

=^

^ 0 / 2

^

Parent(

^

(^2

^

=^

^ 1 / 2

^

Parent(

^

(^3

^

=^

^ 2 / 2

^

Parent(

^

(^4

^

=^

^ 3 / 2

^

Parent(

^

(^5

^

=^

^ 4 / 2

^