Debian Codegraph @

texmf-dist/doc/latex/clrscode3e/clrscode3e.tex

raw
1 \documentclass[11pt]{article}
2 \usepackage{times}
3 \usepackage[mtpcal,mtphrb,zswash,subscriptcorrection]{mtpro2}
4 \usepackage{clrscode3e}
5 \usepackage{url}
6 \urlstyle{rm}
7 \input{page}
8
9 \newcommand{\subheading}[1]{\subsubsection*{#1}}
10 \newcommand{\clrscodethree}{\texttt{clrscode3e}}
11 \newcommand{\Codebox}{\texttt{codebox}}
12 \newcommand{\defn}[1]{\textit{\textbf{#1}}}
13
14 \begin{document}
15
16 \title{Using the \clrscodethree{} Package in \LaTeXe}
17 \author{Thomas H. Cormen \\ [email protected]}
18 \date{February 20, 2018}
19
20 \maketitle
21
22 \section{Introduction}
23 \label{sec:intro}
24
25 This document describes how to use the \clrscodethree{} package in
26 \LaTeXe{} to typeset pseudocode in the style of \textit{Introduction
27 to Algorithms}, Third edition, by Cormen, Leiserson, Rivest, and Stein
28 (CLRS 3/e) \cite{CLRS09}. You use the commands\footnote{We use the
29 term ``command'' rather than ``macro'' throughout this document,
30 though ``macro'' would work just as well.} in the same way we did in
31 writing CLRS 3/e, and your output will look just like the pseudocode
32 in the text.
33
34 \section{Setup}
35 \label{sec:setup}
36
37 To get the \clrscodethree{} package, download
38 \url{http://www.cs.dartmouth.edu/~thc/clrscode/clrscode3e.sty}, and
39 put it where it will be found when you run \LaTeXe{}. To use the
40 package, include the following line in your source file:
41
42 {\small
43 \begin{verbatim}
44 \usepackage{clrscode3e}
45 \end{verbatim}
46 }
47
48 \noindent The \clrscodethree{} package itself includes the line
49
50 {\small
51 \begin{verbatim}
52 \RequirePackage{graphics} % needed for \scalebox command
53 \end{verbatim}
54 }
55
56 \noindent This line is necessary in order to get the right spacing for
57 the $\isequal$ symbol that we use for equality tests. Therefore, you
58 will need to have the \texttt{graphics} package installed and
59 available on your system.
60
61 \section{Typesetting names}
62 \label{sec:names}
63
64 Pseudocode in CLRS 3/e uses four types of names: identifiers,
65 procedures, constants, and fixed functions. We provide commands
66 \verb`\id`, \verb`\proc`, \verb`\const`, and \verb`\func` for these
67 names. Each of these commands takes one argument, which is the name
68 being typeset. These commands work both in and out of math mode.
69 When used in math mode, and when the name given as an argument
70 contains a dash, the dash is typeset as a hyphen rather than as a
71 minus sign.
72
73 \begin{description}
74
75 \item[Identifiers:] Use identifiers for variable names of more than
76 one character. When a variable name is just a single character, e.g.,
77 the identifier~$j$ in line~1 of \proc{Insertion-Sort} on page~18, we
78 just typeset it in math mode rather than using the \verb`\id` command:
79 \verb`$j$`.
80
81 \sloppy
82
83 Do not typeset identifiers consisting of two or more characters, e.g.,
84 the variable \id{key} in line~2 of \proc{Insertion-Sort}, in this way.
85 (See page~51 of Lamport \cite{Lamport93}.) Although \LaTeXe{}
86 provides the \verb`\mathit` command for typesetting multiletter
87 identifiers, use our \verb`\id` command instead: \verb`\id{key}`,
88 rather than \verb`\mathit{key}` or---horrors!---\verb`$key$`. Since
89 the \verb`\id` command may be used both in and out of math mode, the
90 source text
91
92 \fussy
93
94 {\small
95 \begin{verbatim}
96 Line~5 uses the variable \id{key} in the test $A[i] > \id{key}$.
97 \end{verbatim}
98 }
99
100 \noindent will produce
101 \begin{quote}
102 Line~5 uses the variable \id{key} in the test $A[i] > \id{key}$.
103 \end{quote}
104
105 To see how a dash turns into a hyphen, consider line~1 of
106 \proc{Find-Max-Crossing-Subarray} on page~71. It contains the
107 variable \id{left-sum}. Typesetting this variable name by
108 \verb`\id{left-sum}` produces a hyphen in the identifier, but
109 typesetting it by \verb`\mathit{left-sum}` would produce
110 $\mathit{left-sum}$, with a minus sign---rather than a hyphen---in the
111 identifier.
112
113 \item[Procedures:] For procedure names, use the \verb`\proc` command.
114 It typesets procedure names in small caps, and dashes (which occur
115 frequently in our procedure names) are typeset as hyphens. Thus, the
116 source \verb`\proc{Insertion-Sort}` produces \proc{Insertion-Sort}.
117 Since you can use the \verb`\proc` command both in and out of math mode,
118 the source text
119
120 {\small
121 \begin{verbatim}
122 We call \proc{Insertion-Sort} with an array $A$, so that the
123 call is $\proc{Insertion-Sort}(A)$.
124 \end{verbatim}
125 }
126
127 \noindent will produce
128 \begin{quote}
129 We call \proc{Insertion-Sort} with an array $A$, so that the
130 call is $\proc{Insertion-Sort}(A)$.
131 \end{quote}
132
133 \item[Constants:] We typeset constants such as \const{nil},
134 \const{true}, and \const{red} in small caps with the \verb`\const`
135 command, e.g., \verb`\const{nil}`, \verb`\const{true}`, and
136 \verb`\const{red}`. The \verb`\const` command typesets a dash within
137 a constant name as a hyphen, so that, as on page~409,
138 \verb`\const{no-such-path}` will produce $\const{no-such-path}$.
139
140 \item[Fixed functions:] We typeset the names of fixed functions in
141 plain old roman with the \verb`\func` command, e.g., \func{level} and
142 \func{out-degree}. By a ``fixed function,'' we mean a function that
143 is a specific, given function. For example, the $\sin$ function is
144 typically typeset in roman; $\sin x$ looks right, but wouldn't
145 $\id{sin}\ x$ look strange? Yet, on page~44, $\Theta(g(n))$ looks
146 right, but $\Theta(\textrm{g}(n))$ would look wrong, since $g$ is a
147 variable that stands for any one of a number of functions.
148
149 As with the other commands for names, a dash within a function name
150 will typeset as a hyphen, so that \verb`\func{out-degree}` will
151 produce \func{out-degree} rather than $\textrm{out}-\textrm{degree}$.
152 Note that \LaTeXe{} provides commands for many fixed functions, such
153 as $\sin$ and $\log$; Table 3.9 on page~44 of Lamport \cite{Lamport93}
154 lists these ``log-like'' functions.
155
156 \end{description}
157
158 \section{Typesetting object attributes}
159 \label{sec:attributes}
160
161 In the first two editions of the book, we used square brackets for
162 object attributes. For example, we represented the length of an
163 array~$A$ by $\id{length}[A]$. Based on requests from readers, we
164 switched to the object-like dot-notation in the third edition, so that
165 we now denote the length of array~$A$ by \attrib{A}{length}.
166
167 You might think that you could typeset \attrib{A}{length} by
168 \verb`$A.\id{length}$`, but that would produce $A.\id{length}$, which
169 has not quite enough space after the dot. Therefore, we created a set
170 of commands to typeset object attributes. Each one may be used either
171 in or out of math mode.
172
173 Most of the time, we use the \verb`\attrib` command, which takes two
174 arguments: the name of the object and the name of the attribute.
175 Let's make a couple of definitions:
176 \begin{itemize}
177
178 \item An \defn{i-string} is a string that you would use in an
179 \verb`\id` command, typically one or more non-Greek letters, numerals,
180 or dashes.
181
182 \item An \defn{x-string} is a string that you would not use in an
183 \verb`\id` command, typically because it has a subscript or one or
184 more Greek letters.
185
186 \item As a special, and very common, case, a single non-Greek letter
187 can count as either an i-string or an x-string.
188
189 \end{itemize}
190
191 \noindent The \verb`\attrib` command works well when the object name
192 is an x-string and the attribute name is an \mbox{i-string}. For
193 example, to produce \attrib{A}{length}, use \verb`\attrib{A}{length}`.
194 Here, we treat the object name,~$A$, as an x-string. The attribute
195 name, \id{length}, is of course an i-string.
196
197 If all your objects are x-strings and all your attributes are
198 i-strings, then the \verb`\attrib` command will be all you need. We
199 provide several other commands for other situations that arose when we
200 produced CLRS~3/e.
201
202 The four basic attribute commands are \verb`\attribxi`,
203 \verb`\attribxx`, \verb`\attribii`, and \verb`\attribix`. Each takes
204 two arguments: the object name and the attribute name. The last two
205 letters of the command name tell you what type of strings the
206 arguments should be. The next-to-last letter tells you about the
207 object name, and the last letter tells you about the attribute name.
208 \verb`i` indicates that the argument will be treated as an \verb`\id`,
209 in which case the command calls the \verb`\id` command and also puts
210 the right amount of space between the argument and the dot.
211
212 \begin{itemize}
213
214 \item You may use \verb`\attribxi` precisely when you would use
215 \verb`\attrib`. In fact, \verb`\attrib` is just a call to
216 \verb`\attribxi`.
217
218 \item Use \verb`\attribxx` when both the object name and attribute
219 names are x-strings. For example, you would use \verb`\attribxx` if
220 the attribute name has a subscript, so that to produce
221 \attribxx{y}{c_i}, you would use \verb`\attribxx{y}{c_i}`. Another
222 situation in which you would use \verb`\attribxx` is when the
223 attribute name is a Greek letter: to produce \attribxx{v}{\pi}, use
224 \verb`\attribxx{v}{\pi}`.
225
226 \item If both the object name and attribute name are i-strings, then
227 you should use \verb`\attribii`. For example,
228 \verb`\attribii{item}{key}` produces \attribii{item}{key}, and
229 \verb`\attribii{prev-item}{np}` produces \attribii{prev-item}{np}.
230
231 \item If the object name is an i-string and the attribute name is an
232 x-string, then use \verb`\attribix`. (We never had this situation
233 arise in CLRS 3/e.) But if we had wanted to produce
234 \attribix{item}{\pi}, we would have used \verb`\attribix{item}{\pi}`.
235
236 \end{itemize}
237
238 For convenience, the \clrscodethree{} package also contains commands
239 for cascading attributes, such as \attribb{x}{left}{size}. These
240 commands string together calls to the appropriate \verb`\attribxi` and
241 \verb`\attribxx` commands. The number of arguments they take depends
242 on how many attributes you are stringing together.
243
244 \begin{itemize}
245
246 \item When you have two attributes, use \verb`\attribb`, which takes
247 an object name and two attribute names: \verb`\attribb{x}{left}{size}`
248 produces \attribb{x}{left}{size}. This command assumes that the
249 object name is an x-string and both attribute names are i-strings.
250
251 \item For three attributes, use \verb`\attribbb`, which takes an
252 object name (an x-string) and three object names (i-strings): to
253 produce \attribbb{y}{p}{left}{size}, use
254 \verb`\attribbb{y}{p}{left}{size}`.
255
256 \item For four attributes, use \verb`\attribbbb`, which is like
257 \verb`\attribbb` but with one additional attribute tacked on. We
258 never needed to use this command in CLRS 3/e.
259
260 \item The \verb`\attribbxxi` command is for one level of cascading
261 where the first attribute given is an \mbox{x-string}. For example,
262 \verb`\attribbxxi{x}{c_i}{n}` produces \attribbxxi{x}{c_i}{n}.
263
264 \end{itemize}
265
266 If your cascading attributes do not fit any of these descriptions,
267 you'll have to roll your own command from the \verb`\attribxx` and
268 \verb`\attribxi` (or \verb`\attrib`) commands. For example, suppose
269 you want to produce \attribxx{\attribxi{x}{left}}{\id{key_i}}.
270 Because it has a subscript, $\id{key}_i$ is an x-string, and so you
271 should not use \verb`\attribb`. Instead, use
272 \verb`\attribxx{\attribxi{x}{left}}{\id{key_i}}`. (You could replace
273 the call of \verb`\attribxi` by a call of \verb`\attrib`.) Note that
274 this call treats $\id{key_i}$ as an attribute of \attrib{x}{left},
275 which is correct, rather than treating \attribii{left}{\id{key}_i} as
276 an attribute of~$x$, which is not correct.
277
278 Edges of a graph can have attributes, too, and the \clrscodethree{}
279 package provides two commands for attributes of edges. These commands
280 assume that the edges are of the form $(u,v)$, where the vertices $u$
281 and~$v$ are x-strings. They take three parameters: the two vertices
282 that define the edge and the name of the attribute.
283 \begin{itemize}
284
285 \item When the attribute name is an i-string, use \verb`\attribe`.
286 For example, to produce \attribe{u}{v}{c}, use
287 \verb`\attribe{u}{v}{c}`.
288
289 \item When the attribute name is an x-string, use \verb`\attribex`.
290 For example, to produce \attribex{u}{v}{c'}, use
291 \verb`\attribex{u}{v}{c'}`.
292
293 \end{itemize}
294
295 \section{Miscellaneous commands}
296 \label{sec:misc}
297
298 The \clrscodethree{} package contains three commands that don't really
299 fit anywhere else, so let's handle them here. All three must be used
300 in math mode.
301
302 \begin{itemize}
303
304 \item We denote subarrays with the ``$\twodots$'' notation, which is
305 produced by the \verb`\twodots` command. Thus, the source text
306 \verb`$A[1 \twodots j-1]$` will produce $A[1 \twodots j-1]$.
307
308 \item We use the \verb`\gets` command for the assignment operator.
309 For example, line~4 of \proc{Insertion-Sort} on page~18 is
310 \verb`$i \gets j - 1$`, producing $i \gets j - 1$.
311
312 \item We use the \verb`\isequal` command to test for equality with the
313 $\isequal$ symbol. For example, line~1 of
314 \proc{Find-Maximum-Subarray} on page~72 contains the test $\id{high}
315 \isequal \id{low}$, which we get by typesetting
316 \verb`$\id{high} \isequal \id{low}$`.
317
318 \end{itemize}
319
320 You might wonder why we bother with the \verb`\gets` command when we
321 could just typeset an equals sign directly. The answer is that in the
322 first two editions of \textit{Introduction to Algorithms}, we used a
323 different symbol (a left arrow) for the assignment operator, and it
324 made sense to use a command for that. Many readers told us that they
325 preferred to use an equals sign for assignment---as many programming
326 languages use---and so we made this change for the third edition. But
327 it's a good idea to continue using the \verb`\gets` command so that we
328 can easily change our assignment operator should we desire to do so in
329 the future.
330
331 Once we decided to use the equals sign for assignment, we could no
332 longer use it for equality tests. We created the \verb`\isequal`
333 command for equality tests, and we decided to base it on the double
334 equals sign used for equality tests in C, C++, and Java. Typesetting
335 it as \verb`==` in math mode produces $==$, which is too wide for our
336 tastes. Our \verb`\isequal` command calls the \verb`\scalebox`
337 command from the \texttt{graphics} package to narrow the symbol, and
338 it puts a nice amount of space between the equals signs: $\isequal$.
339
340 \section{The \Codebox{} environment}
341 \label{sec:codebox}
342
343 We typeset pseudocode by putting it in a \Codebox{} environment. A
344 \Codebox{} is a section of code that does not break across pages.
345
346 \subheading{Contents of a \Codebox{}}
347
348 Each procedure should go in a separate \Codebox{}, even if you have
349 multiple procedures appearing consecutively. The only possible reason
350 I can think of to put more than one procedure in a single \Codebox{}
351 is to ensure that the procedures appear on the same page. If you
352 really need your procedures to appear on the same page, then you
353 should consider using other means in \LaTeXe, such as the
354 \texttt{minipage} environment. Moreover, if you have written your
355 procedures so that they have to appear on the same page, you should
356 probably be asking yourself whether they are too interdependent.
357
358 The typical structure within a \Codebox{} is as follows. Usually, the
359 first line is the name of a procedure, along with a list of
360 parameters. (Not all \Codebox{}es include procedure names; for
361 example, see the pseudocode on page~343 of CLRS 3/e.) After the line
362 containing the procedure name come one or more lines of code, usually
363 numbered. Some of the lines may be unnumbered, being continuations of
364 previous lines. Lines are usually numbered starting from~1, but again
365 there are exceptions, such as the pseudocode on page~343.
366
367 \subheading{Using \texttt{$\backslash$Procname} to name the procedure}
368
369 The \verb`\Procname` command specifies the name of the procedure. It
370 takes as a parameter the procedure name and parameters, typically all
371 in math mode. \verb`\Procname` makes its argument flush left against
372 the margin, and it leaves a little bit of extra space below the line.
373 For example, here is how we typeset the \proc{Insertion-Sort}
374 procedure on page~18:
375
376 \pagebreak
377
378 {\small
379 \begin{verbatim}
380 \begin{codebox}
381 \Procname{$\proc{Insertion-Sort}(A)$}
382 \li \For $j \gets 2$ \To $\attrib{A}{length}$
383 \li \Do
384 $\id{key} \gets A[j]$
385 \li \Comment Insert $A[j]$ into the sorted sequence
386 $A[1 \twodots j-1]$.
387 \li $i \gets j-1$
388 \li \While $i > 0$ and $A[i] > \id{key}$
389 \li \Do
390 $A[i+1] \gets A[i]$
391 \li $i \gets i-1$
392 \End
393 \li $A[i+1] \gets \id{key}$
394 \End
395 \end{codebox}
396 \end{verbatim}
397 }
398
399 \subheading{Using \texttt{$\backslash$li} and \texttt{$\backslash$zi}
400 to start new lines}
401
402 To start a new, numbered line, use the \verb`\li` command. To start a
403 new, \emph{un}numbered line, use the \verb`\zi` command. Note that
404 since a \Codebox{} is not like the \verb`verbatim` environment, the
405 line breaks within the source text do not correspond to the line
406 breaks in the typeset output.
407
408 \subheading{Tabs}
409
410 I find that it is best to set the tab stops in the text editor to
411 every 4 characters when typing in and displaying pseudocode source
412 with the \clrscodethree{} package. I use emacs, and to get the tabs
413 set up the way I want them, my \mbox{\texttt{tex-mode.el}} file
414 includes the line \verb`(setq tab-width 4)`.
415
416 A \Codebox{} environment has a \verb`tabbing` environment within it.
417 Each tab stop gives one level of indentation. We designed the
418 indentation so that the body of an \kw{else} clause starts at just the
419 right indentation. For the most part, you won't need to be concerned
420 with tabs. The primary exception is when you want to include a
421 comment at the end of a line of pseudocode, and especially when you
422 want to include comments after several lines and you want the comments
423 to vertically align.
424
425 If you used the \texttt{clrscode} package from the second edition of
426 the book, you might notice different tabbing behavior when you port
427 your pseudocode to the \clrscodethree{} package. Where the
428 \texttt{clrscode} package used two tab stops for each level of loop
429 indentation, the \clrscodethree{} package uses just one tab stop. We
430 made this change in the \clrscodethree{} package because the third
431 edition eliminates the keyword \kw{then} and left-aligns \kw{else}
432 with its corresponding \kw{if}.
433
434 Note that the \verb`tabbing` environment within a codebox has nothing
435 to do with tabs that you enter in your source code; when you press the
436 TAB key, that's the same as pressing the space bar in the eyes of
437 \LaTeXe{}.
438
439 \subheading{Commands for keywords}
440
441 As you can see from the source for \proc{Insertion-Sort}, the commands
442 \verb`\For` and \verb`\While` produce the keywords \kw{for} and
443 \kw{while} in boldface within a \Codebox{}.
444
445 Sometimes you want to include a keyword in the main text, as I have
446 done in several places in this document. Use the \verb`\kw` command
447 to do so. For example, to produce the previous paragraph, I typed in
448 the following:
449
450 {\small
451 \begin{verbatim}
452 As you can see from the source for \proc{Insertion-Sort}, the commands
453 \verb`\For` and \verb`\While` produce the keywords \kw{for} and
454 \kw{while} in boldface within a \texttt{codebox}.
455 \end{verbatim}
456 }
457
458 The following commands simply produce their corresponding keywords,
459 typeset in boldface: \verb`\For`, \verb`\To`, \verb`\Downto`,
460 \verb`\By`, \verb`\While`, \verb`\If`, \verb`\Return`, \verb`\Goto`
461 (which does not appear in CLRS 3/e, but you might wish to use),
462 \verb`\Error`, \verb`\Spawn`, \verb`\Sync`, and \verb`\Parfor` (which
463 produces the compound keyword \mbox{\kw{parallel~for}}). Although you
464 could achieve the same effect with the \verb`\kw` command (e.g.,
465 \verb`\kw{for}` instead of \verb`\For`), you will find it easier and
466 more readable to use the above commands in pseudocode. The
467 \verb`\Comment` command simply produces the comment symbol
468 \CommentSymbol, followed by a space. To get the comment symbol
469 without a following space, use \verb`\CommentSymbol`. None of the
470 above commands affects indentation.
471
472 \subheading{Loops}
473
474 The \proc{Insertion-Sort} example above shows typical ways to typeset
475 \kw{for} and \kw{while} loops. In these loops, the important commands
476 are \verb`\Do` and \verb`\End`. \verb`\Do` increments the indentation
477 level to start the body. Put \verb`\Do` on a line starting with
478 \verb`\li`, but don't put either \verb`\li` or \verb`\zi` between the
479 \verb`\Do` command and the first statement of the loop body. Use
480 \verb`\li` or \verb`\zi` in front of all loop-body statements after
481 the first one. \verb`\End` simply decrements the indentation level,
482 and you use it to end any \kw{for} or \kw{while} loop, or otherwise
483 decrement the indentation level.
484
485 In the first two editions of the book, the body of a \kw{for} or
486 \kw{while} loop began with the keyword \kw{do}. Responding to
487 requests from readers to make pseudocode more like C, C++, and Java,
488 we eliminated this keyword in the third edition.
489
490 As you can see from the above example, I like to place each \verb`\Do`
491 and \verb`\End` on its own line. You can format your source text any
492 way you like, but I find that the way I format pseudocode makes it
493 easy to match up \verb`\Do`-\verb`\End` pairs.
494
495 If you want your \kw{for} loop to decrease the loop variable in each
496 iteration, use \verb`\Downto` rather than \verb`\To`. If you want the
497 stride to be a value other than~$1$, use the \verb`\By` command. For
498 example, line~6 of \proc{Iterative-FFT} on page~917 is typeset as
499 \begin{verbatim}
500 \For $k \gets 0$ \To $n-1$ \By $m$
501 \end{verbatim}
502
503 Loops that use the \kw{repeat}-\kw{until} structure are a bit
504 different. We use the \verb`\Repeat` and \verb`\Until`
505 commands, as in the \proc{Hash-Insert} procedure on page~270:
506
507 \pagebreak
508
509 {\small
510 \begin{verbatim}
511 \begin{codebox}
512 \Procname{$\proc{Hash-Insert}(T,k)$}
513 \li $i \gets 0$
514 \li \Repeat
515 \li $j \gets h(k,i)$
516 \li \If $T[j] \isequal \const{nil}$
517 \li \Then
518 $T[j] \gets k$
519 \li \Return $j$
520 \li \Else
521 $i \gets i+1$
522 \End
523 \li \Until $i \isequal m$
524 \li \Error ``hash table overflow''
525 \end{codebox}
526 \end{verbatim}
527 }
528
529 \noindent Note that the \verb`\Until` command has an implied
530 \verb`\End`.
531
532 \subheading{Typesetting \kw{if} statements}
533
534 As you can see from the above example of \proc{Hash-Insert}, we
535 typeset \kw{if} statements with the commands \verb`\If`, \verb`\Then`,
536 \verb`\Else`, and \verb`\End`. In the first two editions of the book,
537 the keyword \kw{then} appeared in pseudocode, but---again mindful of
538 requests from our readers to make our pseudocode more like C, C++, and
539 Java---we eliminated the keyword \kw{then} in the third edition. The
540 \verb`\Then` command remains, however, in order to indent the code
541 that runs when the test in the \kw{if} clause evaluates to
542 \const{true}.
543
544 We use \verb`\End` to terminate an \kw{if} statement, whether or not
545 it has an \kw{else} clause. For an example of an \kw{if} statement
546 without an \kw{else} clause, here's the \proc{Merge-Sort} procedure on
547 page~34:
548
549 {\small
550 \begin{verbatim}
551 \begin{codebox}
552 \Procname{$\proc{Merge-Sort}(A, p, r)$}
553 \li \If $p < r$
554 \li \Then
555 $q \gets \floor{(p + r) / 2}$
556 \li $\proc{Merge-Sort}(A, p, q)$
557 \li $\proc{Merge-Sort}(A, q+1, r)$
558 \li $\proc{Merge}(A, p, q, r)$
559 \End
560 \end{codebox}
561 \end{verbatim}
562 }
563
564 Note: the command \verb`\floor` is our own. It is defined as
565
566 {\small
567 \begin{verbatim}
568 \newcommand{\floor}[1]{\left\lfloor #1 \right\rfloor}
569 \end{verbatim}
570 }
571
572 The \proc{Hash-Insert} procedure above shows how to typeset an \kw{if}
573 statement that has an \kw{else} clause. For a more complicated
574 example, using nested \kw{if} statements, here's the
575 \proc{Cascading-Cut} procedure on page~519:
576
577 \pagebreak
578
579 {\small
580 \begin{verbatim}
581 \begin{codebox}
582 \Procname{$\proc{Cascading-Cut}(H,y)$}
583 \li $z \gets \attrib{y}{p}$
584 \li \If $z \neq \const{nil}$
585 \li \Then
586 \If $\attrib{y}{mark} \isequal \const{false}$
587 \li \Then $\attrib{y}{mark} \gets \const{true}$
588 \li \Else
589 $\proc{Cut}(H,y,z)$
590 \li $\proc{Cascading-Cut}(H,z)$
591 \End
592 \End
593 \end{codebox}
594 \end{verbatim}
595 }
596
597 \noindent Note that \verb`\Then` and \verb`\Else` always follow an
598 \verb`\li` command to start a new numbered line. As with the
599 \verb`\Do` command, don't put either \verb`\li` or \verb`\zi` between
600 \verb`\Then` or \verb`\Else` and the statement that follows.
601
602 As you can see, I line up the \verb`\End` commands under the
603 \verb`\Then` and \verb`\Else` commands. I could just as easily have
604 chosen to line up \verb`\End` under the \verb`\If` command instead. I
605 also sometimes elect to put the ``then'' or ``else'' code on the same
606 source line as the \verb`\Then` or \verb`\Else` command, especially
607 when that code is one short line, such as in line~4 of
608 \proc{Cascading-Cut}.
609
610 Sometimes, you need more complicated ``\kw{if}-ladders'' than you can
611 get from the \verb`\Then` and \verb`\Else` commands. The
612 \proc{Transplant} procedure on page~296 provides an example,
613 and it uses the \verb`\ElseIf` and \verb`\ElseNoIf` commands:
614
615 {\small
616 \begin{verbatim}
617 \begin{codebox}
618 \Procname{$\proc{Transplant}(T, u, v)$}
619 \li \If $\attrib{u}{p} \isequal \const{nil}$
620 \li \Then $\attrib{T}{root} \gets v$
621 \li \ElseIf $u \isequal \attribb{u}{p}{left}$
622 \li \Then $\attribb{u}{p}{left} \gets v$
623 \li \ElseNoIf
624 $\attribb{u}{p}{right} \gets v$
625 \End
626 \li \If $v \neq \const{nil}$
627 \li \Then $\attrib{v}{p} \gets \attrib{u}{p}$
628 \End
629 \end{codebox}
630 \end{verbatim}
631 }
632
633 \noindent For an \kw{if}-ladder, use \verb`\Then` for the first case,
634 \verb`\ElseNoIf` for the last case, and \verb`\ElseIf` followed by
635 \verb`\Then` for all intermediate cases. You use \verb`\ElseNoIf`
636 like you use \verb`\Else` in that it follows an \verb`\li` command,
637 you don't follow it with \verb`\Then`, and, because it terminates an
638 \kw{if}-ladder, it's followed by \verb`\End`. I usually line up the
639 terminating \verb`\End` with \verb`\If`, the \verb`\ElseIf` commands,
640 and \verb`\ElseNoIf`, but the way you line it up won't change the
641 typeset output.
642
643 As another example, here is the \proc{Segments-Intersect} procedure on
644 page~1018:
645
646 \pagebreak
647
648 {\small
649 \begin{verbatim}
650 \begin{codebox}
651 \Procname{$\proc{Segments-Intersect}(p_1, p_2, p_3, p_4)$}
652 \li $d_1 \gets \proc{Direction}(p_3, p_4, p_1)$
653 \li $d_2 \gets \proc{Direction}(p_3, p_4, p_2)$
654 \li $d_3 \gets \proc{Direction}(p_1, p_2, p_3)$
655 \li $d_4 \gets \proc{Direction}(p_1, p_2, p_4)$
656 \li \If $((d_1 > 0 \mbox{ and } d_2 < 0) \mbox{ or }
657 (d_1 < 0 \mbox{ and } d_2 > 0))$ and
658 \Indentmore
659 \zi $((d_3 > 0 \mbox{ and } d_4 < 0) \mbox{ or }
660 (d_3 < 0 \mbox{ and } d_4 > 0))$
661 \End
662 \li \Then \Return \const{true}
663 \li \ElseIf $d_1 \isequal 0$ and $\proc{On-Segment}(p_3, p_4, p_1)$
664 \li \Then \Return \const{true}
665 \li \ElseIf $d_2 \isequal 0$ and $\proc{On-Segment}(p_3, p_4, p_2)$
666 \li \Then \Return \const{true}
667 \li \ElseIf $d_3 \isequal 0$ and $\proc{On-Segment}(p_1, p_2, p_3)$
668 \li \Then \Return \const{true}
669 \li \ElseIf $d_4 \isequal 0$ and $\proc{On-Segment}(p_1, p_2, p_4)$
670 \li \Then \Return \const{true}
671 \li \ElseNoIf \Return \const{false}
672 \End
673 \end{codebox}
674 \end{verbatim}
675 }
676
677 This example also shows our first use of an unnumbered line: the
678 second half of the tests on line~5. We use \verb`\zi` to indicate
679 that we're starting an unnumbered line.
680
681 \subheading{Indentation levels}
682
683 In the \proc{Segments-Intersect} procedure, we indent the unnumbered
684 line after line~5 by one level more than the line above it. We do so
685 with the \verb`\Indentmore` command. The \verb`\End` command
686 following the indented line decrements the indentation level back to
687 what it was prior to the \verb`\Indentmore`. If I had wanted to
688 indent the line by two levels, I would have used two
689 \verb`\Indentmore` commands before the line and two \verb`\End`
690 commands afterward. (Recall that \verb`\End` simply decrements the
691 indentation level.)
692
693 Upon seeing the \verb`\end{codebox}` command, the \Codebox{}
694 environment checks that the indentation level is back to where it was
695 when it started, namely an indentation level of~0. If it is not, you
696 will get a warning message like the following:
697
698 {\small
699 \begin{verbatim}
700 Warning: Indentation ends at level 1 in codebox on page 1.
701 \end{verbatim}
702 }
703
704 \noindent This message would indicate that there is one missing
705 \verb`\End` command. On the other hand, you might have one too many
706 \verb`\End` commands, in which case you would get
707
708 {\small
709 \begin{verbatim}
710 Warning: Indentation ends at level -1 in codebox on page 1.
711 \end{verbatim}
712 }
713
714 \noindent Whenever the indentation level is nonzero upon hitting an
715 \verb`\end{codebox}` command, you'll get a warning telling you what
716 the indentation level was.
717
718 \subheading{Tabs and comments}
719
720 Line~3 of \proc{Insertion-Sort} shows how to make a line that is only
721 a comment. It's a little more tricky to put a comment at the end of a
722 line of code. Using the tab command \verb`\>`, explicitly tab to
723 where you want the comment to begin and then use the \verb`\Comment`
724 command to produce the comment symbol. When several lines contain
725 comments, you probably want them to align vertically. I just add tab
726 characters, using a trial-and-error approach, until I am pleased with
727 the result. For example, here's how we produced the
728 \proc{KMP-Matcher} procedure on page~1005:
729
730 {\footnotesize
731 \begin{verbatim}
732 \begin{codebox}
733 \Procname{$\proc{KMP-Matcher}(T,P)$}
734 \li $n \gets \attrib{T}{length}$
735 \li $m \gets \attrib{P}{length}$
736 \li $\pi \gets \proc{Compute-Prefix-Function}(P)$
737 \li $q \gets 0$\>\>\>\>\>\>\>\>\Comment number of characters matched
738 \li \For $i \gets 1$ \To $n$\>\>\>\>\>\>\>\>\Comment scan the text from left to right
739 \li \Do
740 \While $q>0$ and $\Px{q+1}\ne \Tx{i}$
741 \li \Do $q \gets \pi[q]$\>\>\>\>\>\>\Comment next character does not match
742 \End
743 \li \If $\Px{q+1} \isequal \Tx{i}$
744 \li \Then $q \gets q+1$\>\>\>\>\>\>\Comment next character matches
745 \End
746 \li \If $q \isequal m$\>\>\>\>\>\>\>\Comment is all of $P$ matched?
747 \li \Then
748 print ``Pattern occurs with shift'' $i-m$
749 \li $q \gets \pi[q]$\>\>\>\>\>\>\Comment look for the next match
750 \End
751 \End
752 \end{codebox}
753 \end{verbatim}
754 }
755
756 \noindent All six comments align nicely.
757
758 Note: the commands \verb`\Px` and \verb`\Tx` are our own, with the
759 definitions
760
761 {\small
762 \begin{verbatim}
763 \newcommand{\Px}[1]{P[#1]}
764 \newcommand{\Tx}[1]{T[#1]}
765 \end{verbatim}
766 }
767
768 We used the command \verb`\RComment` to justify a comment against the
769 right margin. We used this command only in the \proc{RB-Insert-Fixup}
770 procedure on page~316 and the \proc{RB-Delete-Fixup} procedure on
771 page~326. For example, here's how we typeset line~5 of
772 \proc{RB-Insert-Fixup}:
773
774 {\small
775 \begin{verbatim}
776 \li \Then
777 $\attribb{z}{p}{color}\gets \const{black}$
778 \RComment case 1
779 \end{verbatim}
780 }
781
782 \subheading{Referencing line numbers}
783
784 The source files for CLRS 3/e contain no absolute references to line
785 numbers. We use \emph{only} symbolic references. The \Codebox{}
786 environment is set up to allow you to place \verb`\label` commands on
787 lines of pseudocode and then reference these labels. The references
788 will resolve to the line numbers. Our convention is that any label
789 for a line number begins with \verb`\li:`, but you can name the labels
790 any way that you like.
791
792 For example, here's how we \emph{really} wrote the
793 \proc{Insertion-Sort} procedure on page~18:
794
795 \pagebreak
796
797 {\small
798 \begin{verbatim}
799 \begin{codebox}
800 \Procname{$\proc{Insertion-Sort}(A)$}
801 \li \For $j \gets 2$ \To $\attrib{A}{length}$
802 \label{li:ins-sort-for}
803 \li \Do
804 $\id{key} \gets A[j]$ \label{li:ins-sort-pick}
805 \label{li:ins-sort-for-body-begin}
806 \li \Comment Insert $A[j]$ into the sorted sequence
807 $A[1 \twodots j-1]$.
808 \li $i \gets j-1$ \label{li:ins-sort-find-begin}
809 \li \While $i > 0$ and $A[i] > \id{key}$
810 \label{li:ins-sort-while}
811 \li \Do
812 $A[i+1] \gets A[i]$ \label{li:ins-sort-while-begin}
813 \li $i \gets i-1$ \label{li:ins-sort-find-end}
814 \label{li:ins-sort-while-end}
815 \End
816 \li $A[i+1] \gets \id{key}$ \label{li:ins-sort-ins}
817 \label{li:ins-sort-for-body-end}
818 \End
819 \end{codebox}
820 \end{verbatim}
821 }
822
823 \noindent Note that any line may have multiple labels. As an example
824 of referencing these labels, here's the beginning of the first item
825 under ``Pseudocode conventions'' on page~19:
826
827 {\small
828 \begin{verbatim}
829 \item Indentation indicates block structure. For example, the body of
830 the \kw{for} loop that begins on line~\ref{li:ins-sort-for} consists
831 of lines
832 \ref{li:ins-sort-for-body-begin}--\ref{li:ins-sort-for-body-end}, and
833 the body of the \kw{while} loop that begins on
834 line~\ref{li:ins-sort-while} contains lines
835 \ref{li:ins-sort-while-begin}--\ref{li:ins-sort-while-end} but not
836 line~\ref{li:ins-sort-for-body-end}.
837 \end{verbatim}
838 }
839
840 \subheading{Setting line numbers}
841
842 On rare occasions, we needed to start line numbers somewhere other
843 than~1. Use the \verb`setlinenumber` command to set the next line
844 number. For example, in Exercise~24.2-2 on page~657, we want the line
845 number to be the same as a line number within the
846 \proc{Dag-Shortest-Paths} procedure on page~655. Here's the source
847 for the exercise:
848
849 {\small
850 \begin{verbatim}
851 Suppose we change line~\ref{li:dag-sp-loop-begin} of
852 \proc{Dag-Shortest-Paths} to read
853
854 \begin{codebox}
855 \setlinenumber{li:dag-sp-loop-begin}
856 \li \For the first $\card{V}-1$ vertices, taken in topologically sorted order
857 \end{codebox}
858 Show that the procedure would remain correct.
859 \end{verbatim}
860 }
861
862 \noindent The \proc{Dag-Shortest-Paths} procedure is
863
864 {\small
865 \begin{verbatim}
866 \begin{codebox}
867 \Procname{$\proc{Dag-Shortest-Paths}(G,w,s)$}
868 \li topologically sort the vertices of $G$ \label{li:dag-sp-topo-sort}
869 \li $\proc{Initialize-Single-Source}(G,s)$ \label{li:dag-sp-init}
870 \li \For each vertex $u$, taken in topologically sorted order
871 \label{li:dag-sp-loop-begin}
872 \li \Do
873 \For each vertex $v \in \attrib{G}{Adj}[u]$
874 \label{li:dag-sp-inner-begin}
875 \li \Do $\proc{Relax}(u,v,w)$ \label{li:dag-sp-loop-end}
876 \End
877 \End
878 \end{codebox}
879 \end{verbatim}
880 }
881
882 Even more rarely (just once, in fact), we needed to set a line number
883 to be some other line number plus an offset. That was in the two
884 lines of pseudocode on page~343, where the first line number had to be
885 one greater than the number of the last line of \proc{Left-Rotate} on
886 page~313. Use the \verb`setlinenumberplus` command:
887
888 {\small
889 \begin{verbatim}
890 \begin{codebox}
891 \setlinenumberplus{li:left-rot-parent}{1}
892 \li $\attrib{y}{size} \gets \attrib{x}{size}$
893 \li $\attrib{x}{size} \gets \attribb{x}{left}{size}
894 + \attribb{x}{right}{size} + 1
895 \end{codebox}
896 \end{verbatim}
897 }
898
899 \noindent Here, the last line of \proc{Left-Rotate} has
900 \verb`\label{li:left-rot-parent}`.
901
902 \subheading{Indenting long argument lists in procedure calls}
903
904 You might find that you have to call a procedure with an argument list
905 so long that the call requires more than one line. When this
906 situation arises, it often looks best to align the second and
907 subsequent lines of arguments with the first argument. The only place
908 we did so was in the $\proc{Sum-Arrays}'$ procedure in Problem~27-1 on
909 page~805.
910
911 To get this style of alignment, use the \verb`\Startalign` and
912 \verb`\Stopalign` commands, in concert with the \verb`\>` command of
913 \LaTeXe{}. The \verb`\Startalign` command takes an argument that is
914 the text string that you wish to align just to the right of. Start
915 each line that you want to indent with \verb`\>`. Use the
916 \verb`\Stopalign` command to restore indentation to its state from
917 before the \verb`\Startalign` command.
918
919 The source code for $\proc{Sum-Arrays}'$ shows how to use these
920 commands:
921
922 \pagebreak
923
924 {\small
925 \begin{verbatim}
926 \begin{codebox}
927 \Procname{$\proc{Sum-Arrays}{$'$}(A, B, C)$}
928 \li $n \gets \attrib{A}{length}$
929 \li $\id{grain-size} \gets\ \ ?$ \>\>\>\>\>\>\Comment to be determined
930 \li $r \gets \ceil{n/\id{grain-size}}$
931 \li \For $k \gets 0$ \To $r-1$
932 \li \Do
933 \Spawn $\proc{Add-Subarray}(A, B, C, k\cdot\id{grain-size}+1,$
934 \Startalign{\Spawn $\proc{Add-Subarray}($}
935 \> $\min((k+1)\cdot\id{grain-size}, n))$
936 \Stopalign
937 \End
938 \li \Sync
939 \end{codebox}
940 \end{verbatim}
941 }
942
943 \noindent The second line of arguments in the call to
944 \proc{Add-Subarray} starts right under the first parameter, $A$, in
945 the call.
946
947 \section{Reporting bugs}
948 \label{sec:bugs}
949
950 If you find errors in the \clrscodethree{} package, please send me
951 email ([email protected]). It would be best if your message
952 included everything I would require to elicit the error myself.
953
954 The \texttt{clrscode3e.sty} file contains the following disclaimer:
955
956 {\small
957 \begin{verbatim}
958 % Written for general distribution by Thomas H. Cormen, March 2009.
959
960 % The author grants permission for anyone to use this macro package and
961 % to distribute it unchanged without further restriction. If you choose
962 % to modify this package, you must indicate that you have modified it
963 % prior to your distributing it. I don't want to get bug reports about
964 % changes that *you* have made!
965 \end{verbatim}
966 }
967
968 \noindent I have enough trouble keeping up with my own bugs; I don't
969 want to hear about bugs that others have introduced in the package!
970
971 \section{Revision history}
972
973 \begin{itemize}
974
975 \item 20 February 2018. Included definitions for the commands
976 \verb`\floor`, \verb`\Px`, and \verb`\Tx`. Changed \verb`\procdecl`
977 and \verb`\procdecltag` commands to \verb`\proc`.
978
979 \item 27 January 2010. Corrected an error in the documentation. The
980 first line after a \verb`\Repeat` command should begin with
981 \verb`\li`.
982
983 \item 23 March 2009. Initial revision of document and code.
984
985 \end{itemize}
986
987 \begin{thebibliography}{9}
988
989 \bibitem{CLRS09} Thomas H. Cormen, Charles E. Leiserson, Ronald L.
990 Rivest, and Clifford Stein. \textit{Introduction to Algorithms},
991 third edition. The MIT Press, 2009.
992
993 \bibitem{Lamport93} Leslie Lamport. \textit{\LaTeX: A Document
994 Preparation System User's Guide and Reference Manual}.
995 Addison-Wesley, 1993.
996
997 \end{thebibliography}
998
999 \end{document}