










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An in-depth exploration of heaps and priority queues, essential data structures in computer science. Topics covered include binary trees, heap properties, heap operations, heap applications, and heap implementation. Learn about the key differences between heaps and binary search trees, and discover how heaps are used in sorting algorithms and priority queues.
Typology: Study notes
1 / 18
This page cannot be seen from the preview
Don't miss anything!











Full, Perfect, Complete
Insert getSmallest
Heapsort Priority queues
Full Binary Tree
Not Allowed
Perfect Binary Tree
All leaves at level h for tree of height h
h = 2 h = 3 h = 4
h = 1
Heaps
Complete binary tree Value at node Smaller than or equal to values in subtrees
X ≤ Y X ≤ Z
Heap & Non-heap Examples
Heaps Non-heaps
Heap Properties
Height = log 2 (n) = O(log(n))
Always at top of heap!
Value at node larger than values in subtrees Heap can track either min or max, but not both
Heap
Insert ( X ) getSmallest ( )
Heapsort Priority queue
Heap Insert Example
Heap Operation – getSmallest()
O( log(n) )
Heap GetSmallest Example
with end of tree1) Replace root children, if larger swap2) Compare node to with smallest child
Heap GetSmallest Example
with end of tree1) Replace root children, if larger swap2) Compare node to with smallest child
Heap Implementation
Array index i starts at 0 Parent(i) = ⎣ ( i – 1 ) / 2 ⎦ LeftChild(i) = 2 × i + RightChild(i) = 2 × i +
Heap Implementation
Parent(1) = ⎣ ( 1 – 1 ) / 2 ⎦ = ⎣ 0 / 2 ⎦ = 0 Parent(2) = ⎣ ( 2 – 1 ) / 2 ⎦ = ⎣ 1 / 2 ⎦ = 0 Parent(3) = ⎣ ( 3 – 1 ) / 2 ⎦ = ⎣ 2 / 2 ⎦ = 1 Parent(4) = ⎣ ( 4 – 1 ) / 2 ⎦ = ⎣ 3 / 2 ⎦ = 1 Parent(5) = ⎣ ( 5 – 1 ) / 2 ⎦ = ⎣ 4 / 2 ⎦ = 2
Heap Implementation
LeftChild(0) = 2 × 0 +1 = 1 LeftChild(1) = 2 × 1 +1 = 3 LeftChild(2) = 2 × 2 +1 = 5
Heap Implementation
RightChild(0) = 2 × 0 +2 = 2 RightChild(1) = 2 × 1 +2 = 4
Heapsort – Insert Values
Heapsort – Remove Values
Heap Application – Priority Queue
Linear data structure First-in First-out (FIFO) Implement as array / linked list Enqueue Dequeue
Heap Application – Priority Queue
Elements are assigned priority value Higher priority elements are taken out first Equal priority elements are taken out in FIFO order Implement as heap Enqueue ⇒ insert( ) Dequeue ⇒ getSmallest( ) (^) Dequeue
Enqueue