Académique Documents
Professionnel Documents
Culture Documents
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
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
return contents
operation argument value size (unordered)
insert P 1 P P
insert Q 2 P Q P
insert E 3 P Q E E
remove max Q 2 P E E
insert X 3 P E X E
insert A 4 P E X A A
insert M 5 P E X A M A
remove max X 4 P E M A A
insert P 5 P E M A P A
insert L 6 P E M A P L A
insert E 7 P E M A P L E A
remove max P 6 E M A P L E A
4
Priority queue API
5
Priority queue applications
6
Priority queue client example
while (StdIn.hasNextLine())
Transaction data
use a min-oriented pq { type is Comparable
String line = StdIn.readLine(); (ordered by $$)
Transaction item = new Transaction(line);
pq.insert(item);
pq contains
if (pq.size() > M) largest M items
pq.delMin();
}
8
Priority queue client example
sort N log N N
elementary PQ MN M
best in theory N M
9
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
10
Priority queue: unordered array implementation
11
Priority queue elementary implementations
unordered array 1 N N
ordered array N 1 1
12
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.
14
A complete binary tree in nature
15
Binary heap representations
Array representation. T
S R
Indices start at 1. P N O A
Take nodes in level order.
No explicit links needed! 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
16
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
17
Binary heap demo
heap ordered
P R
N H O A
E I G
T P R N H O A E I G
18
Binary heap demo
heap ordered
R O
N P G A
E I H
S R O N P G A E I H
19
Promotion in a heap
Scenario. Child's key becomes larger key than its parent's key.
{ 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
21
Demotion in a heap
Scenario. Parent's 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
23
Binary heap: Java implementation
24
Priority queues implementation cost summary
unordered array 1 N N
ordered array N 1 1
25
Binary heap: practical improvements
1 \
X
26
Binary heap: practical improvements
X Y
N O
L K
1 \
E D
27
Binary heap: practical improvements
Multiway heaps.
Complete d-way tree.
Parent's key no smaller than its children's keys.
Swim takes log N compares; sink takes d log N compares.
d d
Sweet spot: d = 4.
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
28
Binary heap: practical improvements
29
n this analysis, we restrict fanout to be a positive power of 2 and element size to be a power of 2. We also re
eap configurations to those in which all of a parents children fit in a single cache block (where ).
Binary
s the values heap:
of that we arepractical
looking at;improvements
for a typical cache block size of 32 bytes, fanout is limited to 4 for 8
elements, and fanout is limited to 8 for 4 byte heap elements. We also restrict our analysis to heap configura
ich the bottom layer of the heap is completely full (where = ).
Caching. Binary heap is not cache friendly.
Heaps are often used in discrete event simulations as a priority queue to store the events. In order to measur
Cache-aligned
rmance of heaps operating as d-heap.
an event queue, we analyze our heaps in the hold model [25]. In the hold m
has been
Funnel heap.
noticed previously that increasing a heaps fanout can reduce the instruction count of its operations [27, Ex. 2
Pg.B-heap.
12, Ex. 7-2 152].
0
block 0 block 1 block 2 block 3
1 2 3 4 0 1 2 3 4 5 6 7 8 9 10 11 12
Siblings
5 6 7 8 9 10 11 12
e 5: The layout of a -heap when four elements fit per cache line and the array is padded to cache-align the
10
30
Priority queues implementation cost summary
unordered array 1 N N
ordered array N 1 1
Fibonacci 1 log N 1
amortized
31
Binary heap considerations
Immutability of keys.
Assumption: client does not change keys while they're on the PQ.
Best practice: use immutable keys.
32
Immutability: implementing in Java
Advantages.
Simplifies debugging.
Safer in presence of hostile code.
Simplifies concurrent programming.
Safe to use as key in priority queue or symbol table.
Disadvantage. Must create new object for each data type value.
34
2.4 P RIORITY Q UEUES
API and elementary implementations
binary heaps
heapsort
Algorithms
event-driven simulation
http://algs4.cs.princeton.edu
Sorting with a binary heap
36
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 A in-place sort. O
R for
plan L E A L M O P
k(2, 11)
Heap construction: build a max-heap with all N keys.
exch(1, 8) exch(1, 2)
Sortdown: repeatedly
S remove
sink(1,
P
7) the maximum key.sink(1, 1)
A
T X O E E E
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
37
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
38
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
39
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. 1
S X exch(1, 6)
sink(1, 5)
M
2 3
T L X A O L R A A M O P
while (N > 1)
M P E E M E E X R S T X
{
exch(a, 1, N--); sink(4, 11) S exch(1, 10)
sink(1, 9)
S exch(1, 4)
sink(1, 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
T L R A O L E A L M O P
M P E E M S T X R S T X
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, 7) O 1
A
sink(1, 11) sink(1, 6)
X 2 3
M E E E
T S 4 5 6 7
A L E P L M O P
P L R A 8 9 10 11
R S T X R S T X
M O E E result (sorted)
result (heap-ordered) 41
Heapsort: constructing (left) and sorting down (right) a heap
Heapsort: Java implementation
42
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
43
Heapsort: mathematical analysis
2 2
1 1 1 1
0 0 0 0 0 0 0 0
44
Heapsort: mathematical analysis
Quicksort: no, quadratic time in worst case. N log N worst-case quicksort possible,
not practical
Heapsort: yes!
Bottom line. Heapsort is optimal for both time and space, but:
Inner loop longer than quicksorts.
Makes poor use of cache.
Not stable. advanced tricks for improving
45
Introsort
Introsort.
Run quicksort.
Cutoff to heapsort if stack depth exceeds 2 lg N.
Cutoff to insertion sort for N = 16.
selection N2 N2 N2 N exchanges
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
47
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
49
Molecular dynamics simulation of hard discs
50
Warmup: bouncing balls
51
Warmup: bouncing balls
t t + dt t + 2 dt t + t
(collision detected) (roll back clock)
53
Time-driven simulation
Main drawbacks.
~ N 2 / 2 overlap checks per time quantum.
Simulation is too slow if dt is very small.
dt too small: excessive computation
May miss collisions if dt is too large.
(if colliding particles fail to overlap when we are looking)
54
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
56
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)
sj
57
Particle-particle collision prediction
Collision prediction.
Particle i: radius s , position (rx , ry ), velocity (vx , vy ).
i i i i i
if v r 0
t = if d < 0
v r + d
- v v
otherwise
d = (v r)2 (v v) (r r 2 ) = i + j
v v = (vx)2 + (vy)2
v = (vx, vy) = (vxi vx j , vyi vy j )
r = (rx, ry) = (rxi rx j , ryi ry j ) r r = (rx)2 + (ry)2
v r = (vx)(rx) + (vy)(ry)
Important note: This is physics, so we wont be testing you on it!
58
Particle-particle collision resolution
Collision resolution. When two particles collide, how does velocity change?
vx j = vx j =Jx vx
(momentum form)
/ mj j Jx / m j
j vx j =Jy vx
vy = vy j / mj Jy / m j
j
J rx J ry 2 mi m j (v r)
Jx = , Jy = , J =
(mi + m j )
impulse due to normal force
(conservation of energy, conservation of momentum)
Important note: This is physics, so we wont be testing you on it!
59
Particle data type skeleton
public Particle(...) { }
60
Particle-particle collision and resolution implementation
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.
62
Event data type
Conventions.
63
Collision system implementation: skeleton
64
Collision system implementation: main event-driven simulation loop
while(!pq.isEmpty())
{
Event event = pq.delMin();
if(!event.isValid()) continue; get next event
Particle a = event.a;
Particle b = event.b;
65
Particle collision simulation example 1
66
Particle collision simulation example 2
67
Particle collision simulation example 3
68
Particle collision simulation example 4
69