23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

For <strong>in</strong>stance, we can use a round rob<strong>in</strong> scheduler to allocate a slice of CPU time to<br />

various applications runn<strong>in</strong>g concurrently on a computer.<br />

We can implement a round rob<strong>in</strong> scheduler us<strong>in</strong>g a queue, Q, by repeatedly<br />

perform<strong>in</strong>g the follow<strong>in</strong>g steps (see Figure 5.5):<br />

1. e ← Q.dequeue()<br />

2. Service element e<br />

3. Q.enqueue(e)<br />

Figure 5.5: The three iterative steps for us<strong>in</strong>g a<br />

queue to implement a round rob<strong>in</strong> scheduler.<br />

The Josephus Problem<br />

In the children's game "hot potato," a group of n children sit <strong>in</strong> a circle pass<strong>in</strong>g an<br />

object, called the "potato," around the circle. The potato beg<strong>in</strong>s with a start<strong>in</strong>g<br />

child <strong>in</strong> the circle, <strong>and</strong> the children cont<strong>in</strong>ue pass<strong>in</strong>g the potato until a leader r<strong>in</strong>gs<br />

a bell, at which po<strong>in</strong>t the child hold<strong>in</strong>g the potato must leave the game after<br />

h<strong>and</strong><strong>in</strong>g the potato to the next child <strong>in</strong> the circle. After the selected child leaves,<br />

the other children close up the circle. This process is then cont<strong>in</strong>ued until there is<br />

only one child rema<strong>in</strong><strong>in</strong>g, who is declared the w<strong>in</strong>ner. If the leader always uses<br />

the strategy of r<strong>in</strong>g<strong>in</strong>g the bell after the potato has been passed k times, for some<br />

fixed value k, then determ<strong>in</strong><strong>in</strong>g the w<strong>in</strong>ner for a given list of children is known as<br />

the Josephus problem.<br />

Solv<strong>in</strong>g the Josephus Problem Us<strong>in</strong>g a Queue<br />

We can solve the Josephus problem for a collection of n elements us<strong>in</strong>g a queue,<br />

by associat<strong>in</strong>g the potato with the element at the front of the queue <strong>and</strong> stor<strong>in</strong>g<br />

elements <strong>in</strong> the queue accord<strong>in</strong>g to their order around the circle. Thus, pass<strong>in</strong>g the<br />

296

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!