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.

Us<strong>in</strong>g the Modulo Operator to Implement a Circular<br />

Array<br />

Implement<strong>in</strong>g this circular view of Q is actually pretty easy. Each time we<br />

<strong>in</strong>crement f or r, we compute this <strong>in</strong>crement as "(f + 1) mod N" or "(r + 1) mod<br />

N," respectively.<br />

Recall that operator "mod" is the modulo operator, which is computed by tak<strong>in</strong>g<br />

the rema<strong>in</strong>der after an <strong>in</strong>tegral division. For example, 14 divided by 4 is 3 with<br />

rema<strong>in</strong>der 2, so 14 mod 4 = 2. Specifically, given <strong>in</strong>tegers x <strong>and</strong> y such that x ≥ 0<br />

<strong>and</strong> y > 0, we have x mod y = x − x/yy. That is, if r = x mod y, then there is a<br />

nonnegative <strong>in</strong>teger q, such that x = qy + r. <strong>Java</strong> uses "%" to denote the modulo<br />

operator. By us<strong>in</strong>g the modulo operator, we can view Q as a circular array <strong>and</strong><br />

implement each queue method <strong>in</strong> a constant amount of time (that is, O(1) time).<br />

We describe how to use this approach to implement a queue <strong>in</strong> Code Fragment<br />

5.14.<br />

Code Fragment 5.14: Implementation of a queue<br />

us<strong>in</strong>g a circular array. The implementation uses the<br />

modulo operator to "wrap" <strong>in</strong>dices around the end of<br />

the array <strong>and</strong> it also <strong>in</strong>cludes two <strong>in</strong>stance variables, f<br />

<strong>and</strong> r, which <strong>in</strong>dex the front of the queue <strong>and</strong> first<br />

empty cell after the rear of the queue respectively.<br />

291

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

Saved successfully!

Ooh no, something went wrong!