24 Priority Queues
24 Priority Queues
http://algs4.cs.princeton.edu
2.4 P RIORITY Q UEUES
‣ API and elementary implementations
‣ binary heaps
‣ heapsort
Algorithms
‣ event-driven simulation
http://algs4.cs.princeton.edu
Collections
symbol table PUT, GET, DELETE binary search tree, hash table
“ Show me your code and conceal your data structures, and I shall
continue to be mystified. Show me your data structures, and I won't
usually need your code; it'll be obvious.” — Fred Brooks
3
Priority queue
insert P 1 P
insert Q 2 P Q
insert E 3 P Q
remove max Q 2 P E
insert X 3 P E
insert A 4 P E
insert M 5 P E
remove max X 4 P E
insert P 5 P E
insert L 6 P E
insert E 7 P E
remove max P 6 E M
4
A sequence of op
Priority queue API
6
Priority queue: client example
Transaction data
type is Comparable
(ordered by $$)
while (StdIn.hasNextLine())
use a min-oriented pq {
String line = StdIn.readLine();
Transaction transaction = new Transaction(line);
pq.insert(transaction);
if (pq.size() > M)
pq now contains
pq.delMin(); largest M items
}
7
Priority queue: client example
sort N log N N
elementary PQ MN M
best in theory N M
8
Priority queue: unordered and ordered array implementation
insert P 1 P P
insert Q 2 P Q P Q
insert E 3 P Q E E P Q
remove max Q 2 P E E P
insert X 3 P E X E P X
insert A 4 P E X A A E P X
insert M 5 P E X A M A E M P X
remove max X 4 P E M A A E M P
insert P 5 P E M A P A E M P P
insert L 6 P E M A P L A E L M P P
insert E 7 P E M A P L E A E E L M P P
remove max P 6 E M A P L E A E E L M P
9
Priority queue: implementations cost summary
unordered array 1 N N
ordered array N 1 1
10
2.4 P RIORITY Q UEUES
‣ API and elementary implementations
‣ binary heaps
‣ heapsort
Algorithms
‣ event-driven simulation
http://algs4.cs.princeton.edu
Complete binary tree
Binary tree. Empty or node with links to left and right binary trees.
12
A complete binary tree in nature
13
Binary heap: representation
Array representation. T
・Indices start at 1.
S R
4 P 5 N 6 O 7 A
8 E 9 I 10 H 11 G
Heap representations
14
Binary heap: properties
T
S R
P N O A
E I H G
1
T
2 S 3 R
4 P 5 N 6 O 7 A
8 E 9 I 10 H 11 G
Heap representations
15
Binary heap demo
heap ordered
P R
N H O A
E I G
T P R N H O A E I G
16
Binary heap demo
heap ordered
R O
N P G A
E I H
S R O N P G A E I H
17
Binary heap: promotion
{ N 5 T O A
while (k > 1 && less(k/2, k)) E I H G
violates heap order
(larger key than parent)
{
exch(k, k/2); 1
T
k = k/2;
2
S R
} parent of node at k is at k/2
} N 5 P O A
E I H G
P R
N H O A
{
T
pq[++N] = x;
swim(N); P R
} N H O A
T
swim up
S R
sink down
N P O A
E I G H
Heap operation
19
Binary heap: demotion
Scenario. A key becomes smaller than one (or both) of its children's.
int j = 2*k; E I N G
Delete max. Exchange root with node at end, then sink it down.
Cost. At most 2 lg N compares.
P R S R
N H O A N P O A
public Key delMax()
exchange key
{ E I G S key to insert E I G H with root
Key max = pq[1];
violates
exch(1, N--); T H heap order
sink(1); P R S R
pq[N+1] = null;
N H
prevent loitering
O A N P O A
return max; remove node
E I G S add key to heap E I G T
} violates heap order from heap
T S
swim up
S R P R
sink down
N P O A N H O A
E I G H E I G
Heap operations
21
Binary heap: Java implementation
22
Priority queue: implementations cost summary
unordered array 1 N N
ordered array N 1 1
23
DELETE-RANDOM FROM A BINARY HEAP
R H
P N G A
E J I
24
Binary heap: practical improvements
27
Binary heap: practical improvements
X Y
N O
L K
E D
28
Binary heap: practical improvements
Multiway heaps.
・Complete d-way tree.
・Parent's key no smaller than its children's keys.
Fact. Height of complete d-way tree on N nodes is ~ logd N.
Y T G
J X P W I K A B D
E H F R S V C L M Q N O
3-way heap
29
Priority queues: quiz 1
How many compares (in the worst case) to insert in a d-way heap?
A. ~ log2 N
B. ~ logd N
C. ~ d log2 N
D. ~ d logd N
E. I don't know.
30
Priority queues: quiz 2
How many compares (in the worst case) to delete-max in a d-way heap?
A. ~ log2 N
B. ~ logd N
C. ~ d log2 N
D. ~ d logd N
E. I don't know.
31
Priority queue: implementation cost summary
unordered array 1 N N
ordered array N 1 1
Fibonacci 1 log N † 1
† amortized
32
Binary heap: considerations
Immutability of keys.
・Assumption: client does not change keys while they're on the PQ.
・Best practice: use immutable keys.
33
Immutability: implementing in Java
Advantages.
・Simplifies debugging.
・Simplifies concurrent programming.
・More secure in presence of hostile code.
・Safe to use as key in priority queue or symbol table.
Disadvantage. Must create new object for each data type value.
35
2.4 P RIORITY Q UEUES
‣ API and elementary implementations
‣ binary heaps
‣ heapsort
Algorithms
‣ event-driven simulation
http://algs4.cs.princeton.edu
Priority queues: quiz 3
A. Insertion sort.
B. Mergesort.
C. Quicksort.
E. I don't know.
37
Priority queues: quiz 4
B. In-place.
C. Stable.
E. I don't know.
38
k(3, 11) exch(1, 9) exch(1, 3)
Heapsort
S
sink(1, 8)
R
sink(1, 2)
E
O X P E A E
T L
Basic plan
R for
A in-place sort. O L E A L M O P
P L R A M L E A L M O P
O E E R S T X R S T X
keys in arbitrary order build max heap sorted result
heap construction
heap construction sortdownsortdown
(in place) (in place)
1
S 1
S exch(1, 7) XO X exch(1,exch(1,
6) 6) M1 A M
sink(1, 6) sink(1,sink(1,
5) 5)
k(1, 211) 2 XO 3 3
O R R T
M T SE S L2 E L E3 E E
TT S
4 4 5 56 7 6 7
T E E
X A X A AP P L
L LRE APR A A4 L A E5 M EO 6 O P O7 P P
9 8 10 9 11 10
P M LL P E R
11
PM L EA M O E E E E R8 S9 R T10S X11T X
R S M T O X R S T X
starting point (arbitrary
starting order) order) starting point (heap-ordered)
starting point (heap-ordered)
O E E point (arbitrary result (sorted)
result (heap-ordered)
sink(5, sink(5, 11)
11) 1 2 3 4 S5 6 7 S8 exch(1,
9 1 2exch(1,
11)
10
3 411511)
6 7T 8 9 T 1 exch(1,
10 11 exch(1, 2 5)3 4 5)
5 6 L
7 8 9 L 10 11
XHeapsort:
A M P constructing
X (left)
T S andP sorting
L R A down
M O (right)
E E a heap
sink(1, sink(1,
10) 10) sink(1,sink(1,
4) 4)
S O R T E L E A E E L M O P R S T X
O O R R P P S S E E E E
T T L L
X A X A O O L LR A R A A A M MO PO P
M P M E P E E E M E M E E X E X R SR TS XT X
39
Heapsort demo
1 S
2 O 3 R
4 T 5 E 6 X 7 A
8 M 9 P 10 L 11 E
S O R T E X A M P L E
1 2 3 4 5 6 7 8 9 10 11
40
Heapsort demo
E E
L M O P
R S T X
A E E L M O P R S T X
1 2 3 4 5 6 7 8 9 10 11
41
sink(5, 11) S exch(1, 11) T
sink(1, 10)
Heapsort: heap construction O R P
T L X A O L R
M P E E M E E X
First pass. Build heap using bottom-up method.
sink(4, 11) S exch(1, 10) S
sink(1, 9)
O R P
for (int k = N/2; k >= 1; k--)
T L X A O L E
sink(a, k, N);
M P E E M E T X
Second pass. 11
S X exch(1,
exch(1, 6)
6) M
sink(5,
sink(5, 11)
11) S exch(1,
exch(1, 11)
11) T exch(1,
exch(1, 5)
5) L
sink(1,
sink(1, 10)
10) sink(1,
sink(1, 4)
4)
O R P S E E
L A L A M P
while (N > 1) T X O R A O
M P E E M E E X R S T X
{
exch(a, 1, N--); sink(4,
sink(4, 11)
11) S exch(1,
exch(1, 10)
sink(1,
10)
sink(1, 9)
9)
S exch(1,
exch(1, 4)
sink(1,
4)
sink(1, 3)
3)
E
O R P R A E
sink(a, 1, N); L X A L E A M O P
T O L
} M P E E M E T X R S T X
sink(3,
sink(3, 11)
11) S exch(1,
exch(1, 9)
9) R exch(1,
exch(1, 3)
3) E
sink(1,
sink(1, 8)
8) sink(1,
sink(1, 2)
2)
O X P E A E
T L R A O L E A L M O P
M P E E M S T X R S T X
sink(2,
sink(2, 11)
11) S exch(1,
exch(1, 8)
8) P exch(1,
exch(1, 2)
2) A
sink(1,
sink(1, 7)
7) sink(1,
sink(1, 1)
1)
T X O E E E
P L R A M L E A L M O P
M O E E R S T X R S T X
exch(1,
exch(1, 7)
7) O 11
A
sink(1,
sink(1, 11)
11) sink(1,
sink(1, 6)
6)
X 22 33
M E E E
T S 44 55 66 77
A L E P L M O P
P L R A 88 99 10
10 11
11
R S T X R S T X
M O E E result (sorted)
result (heap-ordered) 43
Heapsort: constructing (left) and sorting down (right) a heap
Heapsort: Java implementation
44
Heapsort: trace
a[i]
N k 0 1 2 3 4 5 6 7 8 9 10 11
initial values S O R T E X A M P L E
11 5 S O R T L X A M P E E
11 4 S O R T L X A M P E E
11 3 S O X T L R A M P E E
11 2 S T X P L R A M O E E
11 1 X T S P L R A M O E E
heap-ordered X T S P L R A M O E E
10 1 T P S O L R A M E E X
9 1 S P R O L E A M E T X
8 1 R P E O L E A M S T X
7 1 P O E M L E A R S T X
6 1 O M E A L E P R S T X
5 1 M L E A E O P R S T X
4 1 L E E A M O P R S T X
3 1 E A E L M O P R S T X
2 1 E A E L M O P R S T X
1 1 A E E L M O P R S T X
sorted result A E E L M O P R S T X
45
Heapsort: mathematical analysis
2 2
2 2
1 1 1 1
1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
a tricky sum
(see COS 340)
・Quicksort: no, quadratic time in worst case. N log N worst-case quicksort possible,
・Heapsort: yes!
not practical
Bottom line. Heapsort is optimal for both time and space, but:
・Inner loop longer than quicksort’s.
・Makes poor use of cache.
・Not stable. can be improved using
advanced caching tricks
47
Introsort
Introsort.
・Run quicksort.
・Cutoff to heapsort if stack depth exceeds 2 lg N.
・Cutoff to insertion sort for N = 16.
N log N guarantee;
merge ✔ ½ N lg N N lg N N lg N
stable
improves mergesort
timsort ✔ N N lg N N lg N
when preexisting order
quick
N log N probabilistic guarantee;
✔ N lg N 2 N ln N ½N2
fastest in practice
improves quicksort
3-way quick ✔ N 2 N ln N ½N2
when duplicate keys
49
2.4 P RIORITY Q UEUES
‣ API and elementary implementations
‣ binary heaps
‣ heapsort
Algorithms
‣ event-driven simulation
http://algs4.cs.princeton.edu
Molecular dynamics simulation of hard discs
51
Molecular dynamics simulation of hard discs
52
Warmup: bouncing balls
53
Warmup: bouncing balls
t t + dt t + 2 dt t + Δt
(collision detected) (roll back clock)
55
Time-driven simulation
Main drawbacks.
・~ N / 2 overlap checks per time quantum.
2
56
Event-driven simulation
s
resolution (at time t + dt)
velocity after collision = ( − vx , vy)
position after collision = ( 1 − s , ry + vydt)
prediction (at time t)
dt ! time to hit wall
wall at
= distance/velocity (rx , ry )
x=1
= (1 − s − rx )/vx vy
vx
1 − s − rx
58
Particle-particle collision prediction
Collision prediction.
・Particle i: radius s , position (rx , ry ), velocity (vx , vy ).
i i i i i
(vxj', vyj')
mi
si (vxi , vyi )
(rxi , ryi)
(rxi', ryi')
i
time = t time = t + Δt
(vxj , vyj)
σj
59
Particle-particle collision prediction
Collision prediction.
・Particle i: radius s , position (rx , ry ), velocity (vx , vy ).
i i i i i
B7 v · r 0,
t= B7 d < 0,
v· r + d
Qi?2`rBb2
v· v
€ €
Important note: This is physics, so we won’t be testing you on it!
€ € 60
Particle-particle collision resolution
Collision resolution. When two particles collide, how does velocity change?
j vx j" − =Jy vx
vy " = vy j / mj − Jy / m j
j
€ €
J rx J ry 2 mi mj ( v · r)
Jx = , Jy = , J=
s s s (mi + mj )
impulse due to normal force
(conservation of energy, conservation of momentum)
http://algs4.cs.princeton.edu/61event/Particle.java.html
62
Collision system: event-driven simulation main loop
An invalidated event
Main loop.
・Delete the impending event from PQ (min priority = t).
・If the event has been invalidated, ignore it.
・Advance all particles to time t, on a straight-line trajectory.
・Update the velocities of the colliding particle(s).
・Predict future particle-wall and particle-particle collisions involving the
colliding particle(s) and insert events onto PQ.
63
Event data type
Conventions.
64
Particle collision simulation: example 1
65
Particle collision simulation: example 2
66
Particle collision simulation: example 3
67
Particle collision simulation: example 4
68