Skip to content

Commit 1a2968c

Browse files
committed
#249 6.5-9
1 parent 12afe6c commit 1a2968c

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

chapter6/sections/5/9.tex

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,30 @@
1-
\workinprogress % TODO
1+
We implement a first-in, first-out queue using a min-priority queue, that controls what priorities its elements have.
2+
To enable this mechanism, we'll augment the standard min-priority queue with an additional attribute \id{priority}.
3+
This new attribute will be initialized to 1 upon creating the queue, and will be incremented upon inserting a new element to the queue.
4+
By doing so, we can ensure that the earlier an element is enqueued (first-in), the earlier it will be dequeued (first-out).
5+
6+
The procedures below implement the operations \proc{Enqueue} and \proc{Dequeue} using a min-heap representation of a min-priority queue:
7+
8+
\begin{codebox}
9+
\Procname{$\proc{Min-Heap-Enqueue}(A,x,n)$}
10+
\li $\attrib{x}{key}\gets\attrib{A}{priority}$
11+
\li $\proc{Min-Heap-Insert}(A,x,n)$
12+
\li $\attrib{A}{priority}\gets\attrib{A}{priority}+1$
13+
\end{innercodebox}
14+
\begin{innercodebox}
15+
\Procname{$\proc{Min-Heap-Dequeue}(A)$}
16+
\li \Return $\proc{Min-Heap-Extract-Min}(A)$
17+
\end{codebox}
18+
19+
Symmetrically, if we replace the min-priority queue by the max-priority queue, together with the corresponding operations for inserting and extracting elements, we will get the implementation of stack operations \proc{Push} and \proc{Pop}:
20+
21+
\begin{codebox}
22+
\Procname{$\proc{Max-Heap-Push}(A,x,n)$}
23+
\li $\attrib{x}{key}\gets\attrib{A}{priority}$
24+
\li $\proc{Max-Heap-Insert}(A,x,n)$
25+
\li $\attrib{A}{priority}\gets\attrib{A}{priority}+1$
26+
\end{innercodebox}
27+
\begin{innercodebox}
28+
\Procname{$\proc{Max-Heap-Pop}(A)$}
29+
\li \Return $\proc{Max-Heap-Extract-Max}(A)$
30+
\end{codebox}

0 commit comments

Comments
 (0)