2.3: ArrayQueue - An Array-Based Queue
- Page ID
- 8439
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)In this section, we present the ArrayQueue data structure, which implements a FIFO (first-in-first-out) queue; elements are removed (using the \(\mathtt{remove()}\) operation) from the queue in the same order they are added (using the \(\mathtt{add(x)}\) operation).
Notice that an ArrayStack is a poor choice for an implementation of a FIFO queue. It is not a good choice because we must choose one end of the list upon which to add elements and then remove elements from the other end. One of the two operations must work on the head of the list, which involves calling \(\mathtt{add(i,x)}\) or \(\mathtt{remove(i)}\) with a value of \(\mathtt{i}=0\). This gives a running time proportional to \(\mathtt{n}\).
To obtain an efficient array-based implementation of a queue, we first notice that the problem would be easy if we had an infinite array \(\mathtt{a}\). We could maintain one index \(\mathtt{j}\) that keeps track of the next element to remove and an integer \(\mathtt{n}\) that counts the number of elements in the queue. The queue elements would always be stored in
\[ \mathtt{a[j]},\mathtt{a[j+1]},\ldots,\mathtt{a[j+n-1]} \enspace . \nonumber\]
Initially, both \(\mathtt{j}\) and \(\mathtt{n}\) would be set to 0. To add an element, we would place it in \(\mathtt{a[j+n]}\) and increment \(\mathtt{n}\). To remove an element, we would remove it from \(\mathtt{a[j]}\), increment \(\mathtt{j}\), and decrement \(\mathtt{n}\).
Of course, the problem with this solution is that it requires an infinite array. An ArrayQueue simulates this by using a finite array \(\mathtt{a}\) and modular arithmetic. This is the kind of arithmetic used when we are talking about the time of day. For example 10:00 plus five hours gives 3:00. Formally, we say that
\[ 10 + 5 = 15 \equiv 3 \pmod{12} \enspace . \nonumber\]
We read the latter part of this equation as "15 is congruent to 3 modulo 12." We can also treat \(\bmod\) as a binary operator, so that
\[ 15 \bmod 12 = 3 \enspace . \nonumber\]
More generally, for an integer \(a\) and positive integer \(m\), \(a \bmod m\) is the unique integer \(r\in\{0,\ldots,m-1\}\) such that \(a = r + km\) for some integer \(k\). Less formally, the value \(r\) is the remainder we get when we divide \(a\) by \(m\). In many programming languages, including Java, the \(\bmod\) operator is represented using the \(\mathtt{\text{%}}\) symbol.2
Modular arithmetic is useful for simulating an infinite array, since \(\mathtt{i}\bmod \texttt{a.length}\) always gives a value in the range \(0,\ldots,\mathtt{a.length-1}\). Using modular arithmetic we can store the queue elements at array locations
\[ \mathtt{a[j\text{%a.length}]},\mathtt{a[(j+1)\text{%a.length}]},\ldots,\mathtt{a[(j+n-1)\text{%a.length}]} \enspace. \nonumber\]
This treats the array \(\mathtt{a}\) like a circular array in which array indices larger than \(\texttt{a.length}-1\) "wrap around" to the beginning of the array.
The only remaining thing to worry about is taking care that the number of elements in the ArrayQueue does not exceed the size of \(\mathtt{a}\).
T[] a; int j; int n;
A sequence of \(\mathtt{add(x)}\) and \(\mathtt{remove()}\) operations on an ArrayQueue is illustrated in Figure \(\PageIndex{1}\). To implement \(\mathtt{add(x)}\), we first check if \(\mathtt{a}\) is full and, if necessary, call \(\mathtt{resize()}\) to increase the size of \(\mathtt{a}\). Next, we store \(\mathtt{x}\) in \(\mathtt{a[(j+n)\text{%}a.length]}\) and increment \(\mathtt{n}\).
boolean add(T x) { if (n + 1 > a.length) resize(); a[(j+n) % a.length] = x; n++; return true; }
To implement \(\mathtt{remove()}\), we first store \(\mathtt{a[j]}\) so that we can return it later. Next, we decrement \(\mathtt{n}\) and increment \(\mathtt{j}\) (modulo \(\texttt{a.length}\)) by setting \(\mathtt{j}=(\mathtt{j}+1)\bmod \texttt{a.length}\). Finally, we return the stored value of \(\mathtt{a[j]}\). If necessary, we may call \(\mathtt{resize()}\) to decrease the size of \(\mathtt{a}\).
T remove() { if (n == 0) throw new NoSuchElementException(); T x = a[j]; j = (j + 1) % a.length; n--; if (a.length >= 3*n) resize(); return x; }
Finally, the \(\mathtt{resize()}\) operation is very similar to the \(\mathtt{resize()}\) operation of ArrayStack. It allocates a new array, \(\mathtt{b}\), of size \(2\mathtt{n}\) and copies
\[ \mathtt{a[j]},\mathtt{a[(j+1)\text{%a.length}]},\ldots,\mathtt{a[(j+n-1)\text{%a.length}]} \nonumber\]
onto
\[ \mathtt{b[0]},\mathtt{b[1]},\ldots,\mathtt{b[n-1]} \nonumber\]
and sets \(\mathtt{j}=0\).
void resize() { T[] b = newArray(Math.max(1,n*2)); for (int k = 0; k < n; k++) b[k] = a[(j+k) % a.length]; a = b; j = 0; }
\(\PageIndex{1}\) Summary
The following theorem summarizes the performance of the ArrayQueue data structure:
Theorem \(\PageIndex{1}\).
An ArrayQueue implements the (FIFO) Queue interface. Ignoring the cost of calls to \(\mathtt{resize()}\), an ArrayQueue supports the operations \(\mathtt{add(x)}\) and \(\mathtt{remove()}\) in \(O(1)\) time per operation. Furthermore, beginning with an empty ArrayQueue, any sequence of \(m\) \(\mathtt{add(i,x)}\) and \(\mathtt{remove(i)}\) operations results in a total of \(O(m)\) time spent during all calls to \(\mathtt{resize()}\).