41 views

Uploaded by bsgindia82

- AngryBirds Physics
- Advanced Data Structures Notes
- Data Structures Objective Questions and Answers _ Set-3 _ Searchcrone
- GATE-CS 2006
- Csc313 Trees(3)
- Unit 13final
- Lecture 2 (Sorting Algorithms - Part 1).ppt
- dsm
- IIT2007Paper-I.pdf
- DAA
- lecture5.ppt
- Interval
- Chap6-Heaps and Priority Queues
- A Comparison of Sorting Algorithms
- Tut1solution.ps
- Physics
- c8-0
- How to prepare for an interview at Google.
- AP Physics B - Impulse and Momentum
- glancing collision

You are on page 1of 46

API

elementary implementations

binary heaps

heapsort

event-driven simulation

References:

Algorithms in Java, Chapter 9

http://www.cs.princeton.edu/introalgsds/34pq

1

API

elementary implementations

binary heaps

heapsort

event-driven simulation

2

Priority Queues

Basic operations.

• Insert.

• Remove largest. defining ops

• Copy.

• Create.

• Destroy. generic ops

• Test if empty.

3

Priority Queue Applications

4

Priority queue client example

•Fraud detection: isolate $$ transactions.

•File maintenance: find biggest files or directories.

Solution. Use a priority queue.

= new MinPQ<Transaction>();

sort N lg N N

elementary PQ MN M while(!StdIn.isEmpty())

{

binary heap N lg M M String s = StdIn.readLine();

t = new Transaction(s);

best in theory N M pq.insert(t);

if (pq.size() > M)

pq.delMin();

}

while (!pq.isEmpty())

System.out.println(pq.delMin());

5

API

elementary implementations

binary heaps

heapsort

event-driven simulation

6

Priority queue: unordered array implementation

{

private Item[] pq; // pq[i] = ith element on PQ

private int N; // number of elements on PQ

{ pq = (Item[]) new Comparable[maxN]; }

public boolean isEmpty()

{ return N == 0; }

{ pq[N++] = x; }

{

int max = 0;

for (int i = 1; i < N; i++)

if (less(max, i)) max = i;

exch(max, N-1);

return pq[--N];

}

}

7

Priority queue elementary implementations

unordered array 1 N

ordered array N 1

8

API

elementary implementations

binary heaps

heapsort

event-driven simulation

9

Binary Heap

Binary tree.

• Empty or

• Node with links to left and

right trees.

10

Binary Heap

Binary tree.

• Empty or

• Node with links to left and

right trees.

• Keys in nodes.

• No smaller than children’s keys.

11

Binary Heap

Binary tree.

• Empty or

• Node with links to left and

right trees.

• Keys in nodes.

• No smaller than children’s keys.

Array representation.

• Take nodes in level order.

• No explicit links needed since

tree is complete.

12

Binary Heap Properties

13

Binary Heap Properties

• Note: indices start at 1.

• Parent of node at k is at k/2.

• Children of node at k are at 2k and 2k+1.

14

Binary Heap Properties

• Note: indices start at 1.

• Parent of node at k is at k/2.

• Children of node at k are at 2k and 2k+1.

N is a power of 2

N = 16

height = 5

15

Promotion In a Heap

Scenario. Exactly one node has a larger key than its parent.

• Exchange with its parent.

• Repeat until heap order restored.

{

while (k > 1 && less(k/2, k))

{

exch(k, k/2);

k = k/2;

} parent of node at k is at k/2

}

of incompetence.

16

Insert

{

pq[++N] = x;

swim(N);

}

17

Demotion In a Heap

Scenario. Exactly one node has a smaller key than does a child.

• Exchange with larger child.

• Repeat until heap order restored.

{

while (2*k <= N) children of node

{ at k are 2k and 2k+1

int j = 2*k;

if (j < N && less(j, j+1)) j++;

if (!less(k, j)) break;

exch(k, j);

k = j;

}

}

18

Remove the Maximum

{

Item max = pq[1];

exch(1, N--);

sink(1);

pq[N+1] = null; prevent loitering

return max;

}

19

Binary heap implementation summary

{

private Item[] pq;

private int N;

same as array-based PQ,

public MaxPQ(int maxN) but allocate one extra element

{ . . . }

public boolean isEmpty()

{ . . . }

{ . . . }

public Item delMax()

{ . . . }

{ . . . }

private void sink(int k)

{ . . . }

private boolean less(int i, int j)

{ . . . }

private void exch(int i, int j)

{ . . . }

} 20

Binary heap considerations

• replace less() with greater()

• implement greater().

Array resizing

• add no-arg constructor

• apply repeated doubling. leads to O(log N) amortized time per op

Immutability of keys.

• assumption: client does not change keys while they're on the PQ

• best practice: use immutable keys

Other operations.

• remove an arbitrary item.

easy to implement with sink() and swim() [stay tuned]

• change the priority of an item.

21

Priority Queues Implementation Cost Summary

ordered array N 1 1

ordered list N 1 1

unordered array 1 N N

unordered list 1 N N

binary heap lg N lg N 1

Why hopeless?

22

API

elementary implementations

binary heaps

heapsort

event-driven simulation

23

Digression: Heapsort

• Insert items into heap, one at at time.

• Or can use faster bottom-up method; see book.

sink(a, k, N);

• Remove maximum items, one at a time.

• Leave in array, instead of nulling out.

while (N > 1

{

exch(a, 1, N--);

sink(a, 1, N);

}

24

Significance of Heapsort

A. Yes. Heapsort.

Not mergesort? Linear extra space.

Not quicksort? Quadratic time in worst case. O(N log N) worst-case quicksort

possible, not practical.

• inner loop longer than quicksort’s.

• makes poor use of cache memory.

25

Sorting algorithms: summary

selection x N2 / 2 N2 / 2 N2 / 2 N exchanges

quick x N 2

/ 2 2N ln N N lg N

# key comparisons to sort N distinct randomly-ordered

fastest keys

in practice

26

API

elementary implementations

binary heaps

heapsort

event-driven simulation

27

Review

{

public static void main(String[] args)

{

int N = Integer.parseInt(args[0]);

Ball balls[] = new Ball[N];

for (int i = 0; i < N; i++)

balls[i] = new Ball();

while(true)

{

StdDraw.clear();

for (int i = 0; i < N; i++)

{

balls[i].move();

balls[i].draw();

}

StdDraw.show(50);

}

}

}

28

Review

public class Ball

{

private double rx, ry; // position

private double vx, vy; // velocity

checks for

private double radius; // radius

colliding with

public Ball() walls

{ ... initialize position and velocity ... }

public void move()

{

if ((rx + vx < radius) || (rx + vx > 1.0 - radius)) { vx = -vx; }

if ((ry + vy < radius) || (ry + vy > 1.0 - radius)) { vy = -vy; }

rx = rx + vx;

ry = ry + vy;

}

public void draw()

{ StdDraw.filledCircle(rx, ry, radius); }

}

• physics problems: when? what effect?

• CS problems: what object does the checks? too many checks? 29

Molecular dynamics simulation of hard spheres

according to the laws of elastic collision.

• Moving particles interact via elastic collisions with each other,

and with fixed walls.

• Each particle is a sphere with known position, velocity, mass, and radius.

• No other forces are exerted.

diffusion constant atoms and molecules

• Maxwell and Boltzmann: derive distribution of speeds of interacting

molecules as a function of temperature.

• Einstein: explain Brownian motion of pollen grains.

30

Time-driven simulation

Time-driven simulation.

• Discretize time in quanta of size dt.

• Update the position of each particle after every dt units of time, and

check for overlaps.

• If overlap, roll back the clock to the time of the collision, update the

velocities of the colliding particles, and continue the simulation.

t t + dt t + 2 dt t + t

(collision detected) (roll back clock)

31

Time-driven simulation

Main drawbacks.

• N2 overlap checks per time quantum.

• May miss collisions if dt is too large and colliding particles fail to

overlap when we are looking.

• Simulation is too slow if dt is very small.

t t + dt t + 2 dt

32

Event-driven simulation

• Between collisions, particles move in straight-line trajectories.

• Focus only on times when collisions occur.

• Maintain priority queue of collision events, prioritized by time.

• Remove the minimum = get next collision.

when will it collide next with a wall or another particle?

according to laws of elastic collisions.

33

Particle-wall collision

Collision prediction.

• Particle of radius at position (rx, ry).

• Particle moving in unit box with velocity (vx, vy).

• Will it collide with a horizontal wall? If so, when?

if vy = 0

t = ( ry)/vy if vy < 0

(1 ry)/vy if vy > 0

time = t

(rx', ry')

time = t + t

34

Particle-particle collision prediction

Collision prediction.

• Particle i: radius i, position (rxi, ryi), velocity (vxi, vyi).

• Particle j: radius , position (rx , ry ), velocity (vx , vy ).

j j j j j

(vxi', vyi')

(vxj', vyj')

mi

i (vxi , vyi )

(rxi , ryi)

(rxi', ryi')

time = t time = t + t

(vxj , vyj)

j

35

Particle-particle collision prediction

Collision prediction.

• Particle i: radius i, position (rxi, ryi), velocity (vxi, vyi).

• Particle j: radius , position (rx , ry ), velocity (vx , vy ).

j j j j j

if v r 0

t = if d < 0

v r + d

- v v

otherwise

r = (rx, ry) = (rxi rx j , ryi ry j ) r r = (rx)2 + (ry)2

v r = (vx)(rx) + (vy)(ry)

36

Particle-particle collision prediction implementation

{

Particle a = this;

if (a == b) return INFINITY;

double dx = b.rx - a.rx;

double dy = b.ry - a.ry;

double dvx = b.vx - a.vx;

double dvy = b.vy - a.vy;

double dvdr = dx*dvx + dy*dvy;

if(dvdr > 0) return INFINITY;

double dvdv = dvx*dvx + dvy*dvy;

double drdr = dx*dx + dy*dy;

double sigma = a.radius + b.radius;

double d = (dvdr*dvdr) - dvdv * (drdr - sigma*sigma);

if (d < 0) return INFINITY;

return -(dvdr + Math.sqrt(d)) / dvdv;

}

37

Particle-particle collision prediction implementation

{

if (a == null) return;

for(int i = 0; i < N; i++)

{

double dt = a.dt(particles[i]);

if(t + dt <= limit)

pq.insert(new Event(t + dt, a, particles[i]));

}

double dtX = a.dtX();

double dtY = a.dtY();

if (t + dtX <= limit)

pq.insert(new Event(t + dtX, a, null));

if (t + dtY <= limit)

pq.insert(new Event(t + dtY, null, a));

}

38

Particle-particle collision resolution

Collision resolution. When two particles collide, how does velocity change?

vxi = vxi + Jx / mi

vyi = vyi + Jy / mi

Newton's second law

vx j = vx j Jx / m j (momentum form)

vy j = vx j Jy / m j

Jx = , Jy = , J =

(mi + m j )

impulse due to normal force

(conservation of energy, conservation of momentum)

39

Particle-particle collision resolution implementation

{

Particle a = this;

double dx = b.rx - a.rx;

double dy = b.ry - a.ry;

double dvx = b.vx - a.vx;

double dvy = b.vy - a.vy;

double dvdr = dx*dvx + dy*dvy;

double dist = a.radius + b.radius;

double J = 2 * a.mass * b.mass * dvdr / ((a.mass + b.mass) * dist);

double Jx = J * dx / dist;

double Jy = J * dy / dist;

a.vx += Jx / a.mass;

a.vy += Jy / a.mass;

b.vx -= Jx / b.mass;

b.vy -= Jy / b.mass;

a.count++;

b.count++;

}

40

Collision system: event-driven simulation main loop

Initialization.

• Fill PQ with all potential particle-wall collisions

• Fill PQ with all potential particle-particle collisions.

some other collision intervenes

Main loop.

•Delete the impending event from PQ (min priority = t).

•If the event in no longer valid, 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.

41

Collision system: main event-driven simulation loop implementation

{

pq = new MinPQ<Event>(); initialize PQ with

for(int i = 0; i < N; i++) collision events and

predict(particles[i], limit); redraw event

pq.insert(new Event(0, null, null));

while(!pq.isEmpty()) main event-driven

{ simulation loop

Event e = pq.delMin();

if(!e.isValid()) continue;

Particle a = e.a();

Particle b = e.b();

update positions

for(int i = 0; i < N; i++) and time

particles[i].move(e.time() - t);

t = e.time();

else if (a != null && b == null) a.bounceX()

else if (a == null && b != null) b.bounceY();

else if (a == null && b == null)

{

StdDraw.clear(StdDraw.WHITE);

for(int i = 0; i < N; i++) particles[i].draw();

StdDraw.show(20);

if (t < limit)

pq.insert(new Event(t + 1.0 / Hz, null, null));

}

predict(a, limit); predict new

predict(b, limit); events based on

} changes

} 42

java CollisionSystem 200

43

java CollisionSystem < billiards5.txt

44

java CollisionSystem < brownianmotion.txt

45

java CollisionSystem < diffusion.txt

46

- AngryBirds PhysicsUploaded byloicuoi
- Advanced Data Structures NotesUploaded byChinkal Nagpal
- Data Structures Objective Questions and Answers _ Set-3 _ SearchcroneUploaded bySunny Raj
- GATE-CS 2006Uploaded bytomunda
- Csc313 Trees(3)Uploaded byChristopher Miller
- Unit 13finalUploaded byAnonymous bTh744z7E6
- Lecture 2 (Sorting Algorithms - Part 1).pptUploaded byMaricone A. Sta. Maria
- dsmUploaded bynaabarca
- IIT2007Paper-I.pdfUploaded byTghcfggg
- DAAUploaded byJeewan Chinthaka
- lecture5.pptUploaded byAnonymous niE5VQOH
- IntervalUploaded byJo Kont
- Chap6-Heaps and Priority QueuesUploaded byjibiyoun
- A Comparison of Sorting AlgorithmsUploaded bymuskii25
- Tut1solution.psUploaded byNitin Sharma
- PhysicsUploaded byShivam Khandelwal
- c8-0Uploaded byVinay Gupta
- How to prepare for an interview at Google.Uploaded byShashi Kolar
- AP Physics B - Impulse and MomentumUploaded byCarmelle Zia Reyes
- glancing collisionUploaded byJadze Princeton Narag
- Sorting sUploaded byJason
- Leo Computer JournalUploaded bymanuelq9
- Wk 13 L2Uploaded byrizvi098
- Test1 (1)Uploaded bycubicalcube13
- Physics Rjc p1 2013Uploaded bynasyrah
- Algorithims Labmanual 4 SolveUploaded byirfan_chand_mian
- 2007 FinalUploaded bycfsenel
- physics-a comprehensive reviewUploaded byapi-327919403
- 536 Radl Parcel SimulationUploaded byStefan Radl
- AssignmentUploaded byYvonne Ragguett

- AderUploaded bybsgindia82
- A Clustered Index is Like the Contents of a Phone BookUploaded bybsgindia82
- Constraints on Type Parameters (C# Programming Guide) _ Microsoft DocsUploaded bybsgindia82
- SryUploaded bybsgindia82
- Test1.docxUploaded bybsgindia82
- DBMS_RDBMSUploaded bybsgindia82
- Differences DBMS RDBMSUploaded bybsgindia82
- BaekelandUploaded bybsgindia82
- fsfdsdfUploaded bybsgindia82
- data gridUploaded bybsgindia82
- MailUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- TttUploaded bybsgindia82
- Non BlockalgUploaded bybsgindia82
- DeadlockUploaded bybsgindia82
- Factors Affecting Performance of ProgramUploaded bybsgindia82
- Protecting SharedvariablesUploaded bybsgindia82
- Data Copy in Copy OutUploaded bybsgindia82
- Interleaving Single and Multiple ThreadUploaded bybsgindia82

- Msn MsgrUploaded bypangya0510
- 80024188 Benveniste Problems in General LinguisticsUploaded byTolga Elbirlik
- Fan Coils YsUploaded byZaw Moe Khine
- Sundman AlFediagramUploaded byarun_prasath_41
- Aluminum vs. SteelUploaded byاحمد عقل
- CHAPTER 3-PART 2.pptUploaded byHervis Fantini
- Mercant CircleUploaded byKavi Arasu
- Positioning Technologies Schmidt DannertUploaded bygoem1984
- Innovative ECE Final Projects List 2013 SooxmaUploaded byDeep Gandhi
- ares and volumesUploaded byAngelinSavio
- Summacut EnUploaded byFarkhan Yahya
- inceptionUploaded bydassdass22
- ASTM D4767(TriaxialCU).pdfUploaded bygtddy
- Chap 3 Edit Final[1] - DevocionhUploaded bytsam127
- PLSQL_s08_l01_tryUploaded byElijah Phelps
- Characterization of Multi Walled Carbon Nanotubes Catalysts Supports by Point of Zero ChargeUploaded byBryan Dotson
- 040200102 - Vehicle DynamicsUploaded bydeval desai
- controls and instrument engineer or automation engineer or dcsUploaded byapi-79252446
- h13015 Vmax 10k Block File SsUploaded byArnab Sen
- Fluent-Intro_16.0_AL2_Transient.pdfUploaded byAnonymous 8209ZT
- LTH-E1-eUploaded byfsai69
- Acid Bases Salts and Reacting QuantitiesUploaded byDoc_Croc
- Drive APUploaded bysasa
- Ejercicios y Soluciones de Electroneumatica 15Uploaded byAlexander Penado
- RFID pptUploaded bySudhish Nair
- EE sylla.pdfUploaded byAmit Garg
- Artificial Oxygen TreeUploaded byPiyush Narkhede
- Experion HS Configurator Reference Guide R430Uploaded bymojinjo
- 5 2 a a geometricconstraintsUploaded byapi-312566649
- 2887-7540-1-PBUploaded byChirag Kashyap