CPSC 221
Priority Queues, continued
This image reminds us of a ________________, which is one way we can implement ADT
______________________, whose functions include ______________ and ________________,
with running times ______________________.
(2024’s opening slide, kept as it was.) Monday only got as far as defining a heap, so this is the recap, filled in aloud: heap , priority queue , insert and removeMin , \(O(\log n)\) each.
Today
Announcements
Examlet 7 is this week: AVL trees and B-trees (no hashing)
PA3 is due Monday 11/23
Lab Hash is due Sunday 11/22
Today:
Heaps: insert and removeMin, continued
Building a heap all at once
heapSort
Heap Explorer
Live demo (copied from DSCI 221’s heaps lesson). Random Heap, or insert a few values the room calls out, asking before each click where it will land. Then Remove Min a few times. The array under the tree updates with it; the root is at index 1, as on the slides. Speed slider bottom right.
Code:
void heap< T>:: insert( const T & key) {
if ( size == capacity) growArray();
size++;
items[ size] = key;
heapifyUp( size);
}
void heap< T>:: heapifyUp( int cIndex) {
if ( cIndex > _____)
if ( items[ cIndex] ___ items[ parent( cIndex)]) {
swap( __________, __________);
heapifyUp( __________);
}
}
cIndex > 1: stop at the root
items[cIndex] < items[parent(cIndex)]
swap(items[cIndex], items[parent(cIndex)])
heapifyUp(parent(cIndex))
(min)Heap: removeMin
4
5
6
15
9
7
20
16
25
14
12
11
4
5
6
15
9
7
20
16
25
14
12
11
The min is the root. What fills the hole and keeps the tree complete? Only the last leaf can move without leaving a gap: 11 goes to the root.
Then swap it downward with its smaller child while it’s bigger: 11 swaps with 5, then with 9, and stops: its new children, 14 and 12, are both bigger.
\(O(\log n)\) .
Code:
T heap< T>:: removeMin() {
T minVal = items[ 1 ];
items[ 1 ] = items[ size];
size--;
heapifyDown( 1 );
return minVal;
}
void heap< T>:: heapifyDown( int cIndex) {
if ( hasAChild( cIndex)) {
minChildIndex = minChild( cIndex);
if ( items[ cIndex] ___ items[ minChildIndex]) {
swap( __________, __________);
___________________________
}
}
}
items[cIndex] > items[minChildIndex]
swap(items[cIndex], items[minChildIndex])
heapifyDown(minChildIndex);
Why the min child? Swapping with the larger one would put it above the smaller one, breaking the heap property right there.
What have we done?
(2024’s closing picture, kept as it was.)
insert and removeMin in \(O(\log n)\) , beating every list and array option. Next time: building a heap from n keys all at once (buildHeap), and heapSort.
(min)Heap: buildHeap
B
U
I
L
D
H
E
A
P
N
O
W
W
B
U
I
L
D
H
E
A
P
N
O
(As 2024 drew it: W sits outside the array in slot 0, and the last cell is empty, while the tree already shows W at index 12.)
New problem: we’re handed all n keys at once, in an array, in no particular order. Make it a heap. Is BUILDHEAPNOW a heap? No: U > L, I > E, L > A, …
(min)Heap: buildHeap 3 alternatives
B
U
I
L
D
H
E
A
P
N
O
W
B
U
I
L
D
H
E
A
P
N
O
W
2.
void heap< T>:: buildHeap() {
for ( int i= 2 ; i<= size; i++)
heapifyUp( i);
}
3.
void heap< T>:: buildHeap() {
for ( int i= parent( size); i> 0 ; i--)
heapifyDown( i);
}
All three work.
A sorted array is a heap: every parent comes before its children. \(O(n \log n)\) .
heapifyUp each key in turn, top to bottom: like n inserts. \(O(n \log n)\) .
heapifyDown every non-leaf, from the last parent back up to the root. Leaves are already heaps, so start at parent(size). \(O(n)\) : next slide.
Run 3 on BUILDHEAPNOW: parent(12) = 6, so start at H (index 6), then L, I, U, B. Result: A B E L D H I U P N O W.
buildHeap Explorer
Starts from BUILDHEAPNOW, the array on the previous slide. The dropdown picks alternative 3 (heapifyDown, i from parent(size) down to 1) or alternative 2 (heapifyUp, i from 2 up to size); the red i under the array is the loop index. Step pauses at every comparison.
On BUILDHEAPNOW: heapifyDown takes 5 swaps and gives ABELDHIUPNOW (the next slide’s heap); heapifyUp takes 7 and gives a different heap, ABEDLIHUPNOW. Random Array (10-15 keys) to compare the counts again. Ask: why does heapifyDown skip the leaves?
(min)Heap: buildHeap
A
B
E
L
D
H
I
U
P
N
O
W
A
B
E
L
D
H
I
U
P
N
O
W
Proof of solution to the recurrence:
Thm: buildHeap on an array of size \(n\) runs in time ________.
Time is proportional to the sum of the heights of all the nodes. Call it \(S(h)\) .
\(S(h) =\)
\(S(0) =\)
Soln \(S(h) =\)
But running times are reported in terms of \(n\) , the number of nodes…
Thm: \(O(n)\) .
Each heapifyDown at a node costs at most its height. For a perfect tree of height \(h\) :
\(S(h) = 2S(h-1) + h\)
\(S(0) = 0\)
Soln: \(S(h) = 2^{h+1} - h - 2\)
Induction: \(2(2^h - (h-1) - 2) + h = 2^{h+1} - h - 2\) .
In terms of n: we need an upper bound on the time, so we need a lower bound on n. A heap of height \(h\) has at least \(2^h\) nodes (\(n \ge 2^h\) ), so \(S(h) = 2^{h+1} - h - 2 \le 2^{h+1} = 2 \cdot 2^h \le 2n\) . \(O(n)\) .
(min)Heap: heapSort
A
B
E
L
D
H
I
U
P
N
O
W
A
B
E
L
D
H
I
U
P
N
O
W
Why do we need another sorting algorithm?
(The answers below are a reconstruction: 2024’s slide is blank here.)
buildHeap: \(O(n)\)
removeMin \(n\) times, each removed key going into the cell the heap just gave up at the end: \(O(n \log n)\)
The array now runs largest to smallest (it’s a min-heap): reverse it, \(O(n)\) . Or use a max-heap and skip this step.
Running time: \(O(n \log n)\) .
Why another sort?
In place: \(O(1)\) extra memory (merge sort needs \(O(n)\) )
\(O(n \log n)\) in the worst case (quicksort can hit \(O(n^2)\) )
heapSort Explorer
Starts from the heapSort slide’s heap, ABELDHIUPNOW. Remove Min: the min drops into the cell the heap just gave up at the end of the array (grey, “removed”), and the last key goes to the root and heapifies down. Sort All runs it to the end: the array reads WUPONLIHEDBA, largest to smallest, which is why step 3 reverses it (or uses a max-heap).