Professional Documents
Culture Documents
Slides 24PriorityQueues PDF
Slides 24PriorityQueues PDF
Algorithms
F O U R T H
E D I T I O N
heapsort
event-driven simulation
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
heapsort
event-driven simulation
Priority queue
Collections. Insert and delete items. Which item to delete?
Stack. Remove the item most recently added.
Queue. Remove the item least recently added.
Randomized queue. Remove a random item.
Priority queue. Remove the largest (or smallest) item.
operation argument
insert
insert
insert
remove max
insert
insert
insert
remove max
insert
insert
insert
remove max
return
value size
P
Q
E
Q
X
A
M
X
P
L
E
P
1
2
3
2
3
4
5
4
5
6
7
6
contents
(unordered)
P
P
P
P
P
P
P
P
P
P
P
E
Q
Q
E
E
E
E
E
E
E
E
M
E
X
X
X
M
M
M
M
A
A
A
A
A
A
A
P
M
P
P
P
L
L
L
E
P
P
E
E
E
A
A
A
A
A
A
A
3
boolean isEmpty()
Key max()
int size()
Event-driven simulation.
Numerical computation.
Data compression.
Graph searching.
Number theory.
Artificial intelligence.
Statistics.
Operating systems.
Discrete optimization.
Spam filtering.
N huge, M large
644.08
4121.85
2678.40
4409.74
837.42
3229.27
4732.35
4381.21
66.10
4747.08
2156.86
1025.70
2520.97
708.95
3532.36
4050.20
% java TopM
Thompson
vonNeumann
vonNeumann
Hoare
vonNeumann
5 < tinyBatch.txt
2/27/2000 4747.08
2/12/1994 4732.35
1/11/1999 4409.74
8/18/1992 4381.21
3/26/2002 4121.85
sort key
N huge, M large
use a min-oriented pq
while (StdIn.hasNextLine())
{
String line = StdIn.readLine();
Transaction item = new Transaction(line);
pq.insert(item);
pq contains
if (pq.size() > M)
largest M items
pq.delMin();
}
Transaction data
type is Comparable
(ordered by $$)
implementation
time
space
sort
N log N
elementary PQ
MN
binary heap
N log M
best in theory
operation argument
insert
insert
insert
remove max
insert
insert
insert
remove max
insert
insert
insert
remove max
return
value size
P
Q
E
Q
X
A
M
X
P
L
E
P
1
2
3
2
3
4
5
4
5
6
7
6
contents
(unordered)
P
P
P
P
P
P
P
P
P
P
P
E
Q
Q
E
E
E
E
E
E
E
E
M
contents
(ordered)
E
X
X
X
M
M
M
M
A
A
A
A
A
A
A
P
M
P
P
P
L
L
L
E
P
P
E
E
E
A
A
A
A
A
A
A
Q
P
P
P
E
E
E
E
E
E
E
Q
X
P
M
M
M
L
E
E
X
P
P
P
M
L
L
X
P
P
M
M
P
P
P
no generic
array creation
10
insert
del max
max
unordered array
ordered array
goal
log N
log N
log N
11
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
heapsort
event-driven simulation
13
14
Keys in nodes.
Parent's key no smaller than
children's keys.
i
a[i]
0
-
1
T
2
S
3
R
4
P
5
N
6
O
7
A
8
E
9 10 11
I H G
Array representation.
Indices start at 1.
Take nodes in level order.
No explicit links needed!
8 E
9 I
T
3 R
2 S
4 P
5 N
10 H
6 O
7 A
11 G
Heap representations
15
0
-
1
T
2
S
3
R
4
P
5
N
6
O
7
A
8
E
9 10 11
I H G
8 E
9 I
T
3 R
2 S
4 P
5 N
10 H
6 O
7 A
11 G
Heap representations
16
Promotion in a heap
Scenario. Child's key becomes larger key than its parent's key.
To eliminate the violation:
P
5
N
E
A
violates heap order
(larger key than parent)
G
1
T
2
S
5 P
N
E
Insertion in a heap
Insert. Add node at end, then swim it up.
Cost. At most 1 + lg N compares.
insert
remo
T
R
P
N
H
I
O
S
key to insert
T
R
P
N
E
H
I
S
T
swim up
S
N
E
P
I
sink down
A
Heap operation
18
Demotion in a heap
Scenario. Parent's key becomes smaller than one (or both) of its children's.
To eliminate the violation:
H
5
P
E
G
T
P
E
10
T
R
P
N
H
G
O
S
N
E
key to insert
P
I
P
I
R
P
G
remove node
from heap
T
S
S
N
violates
heap order
prevent loitering
O
A
exchange key
with root
H
R
swim up
key to remove
sink down
N
H
I
Heap operations
20
heap ordered
G
21
heap ordered
H
22
fixed capacity
(for simplicity)
PQ ops
}
23
implementation
insert
del max
max
unordered array
ordered array
binary heap
log N
log N
d-ary heap
logd N
d logd N
Fibonacci
impossible
log N
1
1
1
why impossible?
amortized
24
Assumption: client does not change keys while they're on the PQ.
Best practice: use immutable keys.
Underflow and overflow.
leads to log N
amortized time per op
(how to make worst case?)
25
Immutability: properties
Data type. Set of values and operations on those values.
Immutable data type. Can't change the data type value once created.
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.
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
heapsort
event-driven simulation
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
heapsort
event-driven simulation
11)
exch(1, 10)
sink(1, 9)
S
R
Heapsort
L
11)
X
L
2
4
A
8
heap construction
11)
exch(1, 8)
sink(1, 7)
S
X
L
11)
10
7
(in
L6 place)
E
E
(heap-ordered)
RP
SP
SE
E
T
P
8
M
RM
exch(1,ex
sink(1,si
AAP
XRO
E
E
TE EX
starting point (heap-ordered)
SPO
T
LO
9
3R
EP
SE
P
SE
A
T
ex
exch(1,s
sink(1,
1S
10 E
TE
L
ML
6X
RO
11E
X
X
sink(3, 11)
exch(1, 10)
A
7
AP
A
R
result (sorted)
sink(4, 11)
AP
RSE
LM
L
sorted
R resultE
(in place)
A
SX
sink(4, 11)
exch(1, 11)
sink(1, 10)
AE
XO
11
LTP
RMM
LX
10
EM
EX
L
T
starting point (arbitrary order)
sortdown
RM
11
RE
E
OT
E
M
X
T
SL
RP
starting point (arbitrary order)
S
R
AE
exch(1,
7)
sink(5, 11)
sink(1, 6)
A
O
exch(1,
2) 11)
sink(5,
sink(1, 1)
SE
LT
O build a 3max-heap
E
R
exch(1, 3)
sink(1, 2)
heap construction
M
S
sink(1, 8)
E
A
exch(1, 4)
sink(1, 3)
30
e
exch(1,s
Heapsort demo
Heap construction. Build max heap using bottom-up method.
we assume array entries are indexed 1 to N
10
11
10
11
31
Heapsort demo
Sortdown. Repeatedly delete the largest remaining item.
10
11
32
sink(5, 11)
exch(1, 11)
sink(1, 10)
O
L
sink(4, 11)
4
8
3
5
T
9
O
10
R
7
11
E
L
P
M
starting point (arbitrary order)
sink(5, 11)
OO
LE
L
O
E
X
L E
SM
S
R
L
R
O
L E
SM
T O X P
A A
A
A
exch(1, 7)
sink(1, 6)
exch(1, 4)
M E
sink(1, 3)
X
S
E
E
O
X
T
E
result (heap-ordered)
E
S
E M
R
E
exch(1, 8)
sink(1, 7)
exch(1, 5)
O L
sink(1, 4)
L
L
P
O
SA
A
A
T
P
M
M
sink(1, 11)
exch(1, 10)
sink(1, 9)
R
R
T
P
M
M
sink(4, 11)
L
L
T
P
X
S
exch(1, 9)
8)
exch(1,sink(1,
6)
M
sink(1, 5)
P
E
E
P
E
E
O
starting point (heap-ordered)
sink(2, 11)
S
M
M
R
L
O
T
S
X
exch(1, 11)T
sink(1, 10)
O
T
sortdown
sink(3, 11)
heap construction
1
S
P
exch(1, 10)
sink(1, 9)
L
P
O
M
X
E
T O X P
X
33
Heapsort: constructing (left) and sorting down
sink(3, 11)
exch(1, 9)
exch(1, 3)
Heapsort: sortdown
sortdown
heap construction
Second pass.
10
11
E
L
P
M
starting point (arbitrary order)
sink(5, 11)
sink(4, 11)
exch(1, 10)
sink(1, 9)
sink(3, 11)
exch(1, 9)
sink(1, 8)
L
E
sink(2, 11)
T
L
sink(1, 11)
1
2
E
X
P
8
E
E
O
result (heap-ordered)
Heapsort: constructing (left) and sorting down (right) a heap
L
9
A
3
E
5
10
O
X
E
L
A
R
L
R
M
S
exch(1, 7)
sink(1, 6)
E
L
exch(1, 2)
sink(1, 1)
M
R
T
P
L
R
exch(1, 8)
sink(1, 7)
E
L
exch(1, 3)
sink(1, 2)
L
R
P
A
E
X
T
P
exch(1, 4)
sink(1, 3)
O
M
M
S
L
E
O
X
S
L
exch(1, 5)
sink(1, 4)
E
E
O
starting point (heap-ordered)
T
M
M
L
exch(1, 11)
sink(1, 10)
while (N > 1)
{
exch(a, 1, N--);
sink(a, 1, N);
}
exch(1, 6)
sink(1, 5)
E
7
11
X
T
result (sorted)
34
35
Heapsort: trace
N
k
initial values
11
5
11
4
11
3
11
2
11
1
heap-ordered
10
9
8
7
1
1
1
1
6
1
5
1
4
1
3
1
2
1
1
1
sorted result
1
S
S
S
S
S
X
X
T
S
R
P
2
O
O
O
O
T
T
T
P
P
P
O
3
R
R
R
X
X
S
S
S
R
E
E
a[i]
4 5
T E
T L
T L
T L
P L
P L
P L
O L
O L
O L
M L
O
M
L
E
E
A
A
M
L
E
A
A
E
E
E
E
E
E
E
E
E
A
A
A
L
L
L
L
L
E
M
M
M
M
M
6
X
X
X
R
R
R
R
R
E
E
E
7
A
A
A
A
A
A
A
A
A
A
A
8 9 10 11
M P L E
M P E E
M P E E
M P E E
M O E E
M O E E
M O E E
M E E X
M E T X
M S T X
R S T X
E
O
O
O
O
O
O
P
P
P
P
P
P
P
R
R
R
R
R
R
R
S
S
S
S
S
S
S
T
T
T
T
T
T
T
X
X
X
X
X
X
X
36
Heapsort animation
50 random items
algorithm position
in order
not in order
http://www.sorting-algorithms.com/heap-sort
37
Bottom line. Heapsort is optimal for both time and space, but:
inplace?
selection
insertion
shell
quick
3-way quick
merge
stable?
???
average
/2
/2
/2
/4
?
N
/2
best
N
/2
remarks
N exchanges
2 N ln N
N lg N
heap
worst
N lg N
N lg N
N lg N
2 N lg N
2 N lg N
N lg N
N lg N
N lg N
N lg N
39
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
heapsort
event-driven simulation
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
heapsort
event-driven simulation
42
Moving particles interact via elastic collisions with each other and walls.
Each particle is a disc with known position, velocity, mass, and radius.
No other forces.
temperature, pressure,
diffusion constant
motion of individual
atoms and molecules
44
// position
// velocity
// radius
velocity */
Time-driven simulation
If overlap, roll back the clock to the time of the collision, update the
velocities of the colliding particles, and continue the simulation.
t + dt
t + 2 dt
(collision detected)
t + t
(roll back clock)
46
Time-driven simulation
Main drawbacks.
Event-driven simulation
Change state only when something happens.
48
Particle-wall collision
Collision prediction and resolution.
wall at
x=1
(rx , ry )
vx
vy
1 s rx
49
(vxi', vyi')
(vxj', vyj')
mi
si
(vxi , vyi )
(rxi , ryi)
(rxi', ryi')
i
time = t
time = t + t
(vxj , vyj)
sj
j
50
t =
v r + d
v v
if v r 0
if d < 0
otherwise
d = (v r)2 (v v) (r r 2 )
= i + j
v v = (vx)2 + (vy)2
r r = (rx)2 + (ry)2
v r = (vx)(rx) + (vy)(ry)
2 mi m j (v r)
J rx
J ry
Jx =
, Jy =
, J =
(mi + m j )
impulse due to normal force
(conservation of energy, conservation of momentum)
//
//
//
//
//
position
velocity
radius
mass
number of collisions
public Particle(...) { }
public void move(double dt) { }
public void draw()
{ }
public double timeToHit(Particle that) { }
public double timeToHitVerticalWall()
{ }
public double timeToHitHorizontalWall() { }
public void bounceOff(Particle that)
public void bounceOffVerticalWall()
public void bounceOffHorizontalWall()
{ }
{ }
{ }
predict collision
with particle or wall
resolve collision
with particle or wall
53
no collision
Initialization.
An invalidated event
Main loop.
55
particle-particle collision.
particle-wall collision.
redraw event.
create event
ordered by time
}
invalid if
intervening
collision
56
{ }
}
57
null
null
null
null
&&
&&
&&
&&
b
b
b
b
!=
==
!=
==
null)
null)
null)
null)
initialize PQ with
collision events and
redraw event
a.bounceOff(b);
a.bounceOffVerticalWall()
b.bounceOffHorizontalWall();
redraw();
update positions
and time
process event
}
}
58
59
60
61
62
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
heapsort
event-driven simulation
Algorithms
Algorithms
F O U R T H
E D I T I O N
heapsort
event-driven simulation