




























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























Overview
Full, Perfect, Complete
Insert getSmallest
Heapsort Priority queues
Perfect Binary Tree
All leaves at level
h for tree of height
h
h = 2
h = 4
h = 3
h = 1
Complete Binary Trees
Perfect tree to level
h-
Leaves at level
h
are as far
left
as possible
h = 2
h = 3
h = 1
Heaps
Complete binary tree Value at node
Smaller than or equal to values in subtrees
≤≤≤≤^
≤≤≤≤^
Heap & Non-heap Examples
Heaps
(^6) Non-heaps
Heap
Insert (
getSmallest ( )
Heapsort Priority queue
Heap Operations – Insert( X )
Add X to end of tree
2.^
While (X < parent)
Swap X with parent
// X bubbles up tree
Heap Insert Example
Insert toend of tree
Compare to parent,swap if parent key larger
Insertcomplete
Heap Operation – getSmallest()
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
Heap GetSmallest Example
Replace rootwith end of tree
Compare node tochildren, if larger swapwith smallest child
Repeat swap
if needed
Heap Implementation
Store nodes in array elements Assign location (index) for elements using formula
Heap Implementation
Array index
i^ starts at 0
Parent(
i) =
(^ i
LeftChild(
i) = 2
i^ +
RightChild(
i) = 2
i^ +
Heap Implementation
Parent(
Parent(
Parent(
Parent(
Parent(