Algorithms PDF
Algorithms PDF
Rogrio Brito
rbrito@ime.usp.br
August 24, 2009
Contents
1 Introduction 1 3.11 Printing Messages . . . . 8
3.12 Comments . . . . . . . . 9
2 Installation 2 3.13 An Example . . . . . . . 9
3.14 Options/Customization 10
3 Environment: algorithmic 2
3.1 The Simple Statement . 3 4 Environment: algorithm 14
3.2 The if-then-else Statement 3 4.1 General . . . . . . . . . . 14
3.3 The for Loop . . . . . . . 4 4.2 An Example . . . . . . . 14
3.4 The while Loop . . . . . 5 4.3 Options . . . . . . . . . . 15
3.5 The repeat-until Loop . . 5 4.4 Customization . . . . . . 15
3.6 The Infinite Loop . . . . 6
5 References in Algorithms 16
3.7 The Logical Connectives 6
3.8 The Precondition . . . . 7 6 Known Issues 17
3.9 The Postcondition . . . . 7
3.10 Returning Values . . . . 8 7 General Hints 18
List of Algorithms
1 Calculate y = x n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2 Calculate y = x n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1 Introduction
This package provides two environments, algorithmic and algorithm, which
are designed to be used together but may, depending on the necessities of the
user, be used separately.
This document corresponds to algorithms v0.1, dated 2009/08/24.
1
The algorithmic environment provides an environment for describing al-
gorithms and the algorithm environment provides a float wrapper for algo-
rithms (implemented using algorithmic or some other method at the userss
option). The reason for two environments being provided is to allow the user
maximum flexibility.
This work may be distributed and/or modified under the conditions of the
GNU Lesser General Public License, either version 2 of the License, or (at your
option) any later version, as published by the Free Software Foundation. See the
file COPYING included in this package for further details.
Currently, this package consists of the following files:
algorithms.ins: the driver file
algorithms.dtx: the source file
COPYING: the license file
README: remarks about the package
THANKS: mentions of thanks for contributors to the package
Starting with with the 2009-08-24 release, the package is now versioned and
this document corresponds to version v0.1.
If you use this package, the author would kindly appreciate if you mentioned
it in your documents, so as to let the package be better known and have more
contributors, to make it better for the community itself. This is not required by
the license: its just a friendly request.
2 Installation
The installation procedure of algorithms follows the usual practice of packages
shipped with a pair of .ins/.dtxsimply type the comand:
latex algorithms.ins
and the .sty files will be generated. Copy them to a place that is referenced by
your LATEX distribution. To generate the documentation, type:
latex algorithms.dtx
2
3.1 The Simple Statement
The simple statement takes the form
\STATE <text>
would produce
S0
With line numbering selected for every line, using,
\begin{algorithmic}[1]
\STATE $S \leftarrow 0$
\end{algorithmic}
we would get
1: S 0
3
\STATE do something else
\ELSE
\STATE do the default actions
\ENDIF
\end{algorithmic}
would produce
if some condition is true then
do some processing
else if some other condition is true then
do some different processing
else if some even more bizarre condition is met then
do something else
else
do the default actions
end if
with appropriate indentations.
For example,
\begin{algorithmic}
\FOR{$i=0$ to $10$}
\STATE carry out some processing
\ENDFOR
\end{algorithmic}
produces
for i = 0 to 10 do
carry out some processing
end for
and
\begin{algorithmic}[1]
\FORALL{$i$ such that $0\leq i\leq 10$}
\STATE carry out some processing
\ENDFOR
\end{algorithmic}
produces
4
1: for all i such that 0 i 10 do
2: carry out some processing
3: end for
For example,
\begin{algorithmic}
\WHILE{some condition holds}
\STATE carry out some processing
\ENDWHILE
\end{algorithmic}
produces
while some condition holds do
carry out some processing
end while
5
For example,
\begin{algorithmic}
\REPEAT
\STATE carry out some processing
\UNTIL{some condition is met}
\end{algorithmic}
produces
repeat
carry out some processing
until some condition is met
For example,
\begin{algorithmic}
\LOOP
\STATE this processing will be repeated forever
\ENDLOOP
\end{algorithmic}
produces
loop
this processing will be repeated forever
end loop
6
\IF{\NOT ($year \bmod 400$ \XOR $year \bmod 100$ \XOR $year \bmod 4$)}
\STATE $year$ does not represent a leap year.
\ENDIF
\end{algorithmic}
produces
if not (year mod 400 xor year mod 100 xor year mod 4) then
year does not represent a leap year.
end if
For example,
\begin{algorithmic}
\REQUIRE $x \neq 0$ and $n \geq 0$
\end{algorithmic}
produces
Require: x 6= 0 and n 0
For example,
\begin{algorithmic}
\ENSURE $x \neq 0$ and $n \geq 0$
\end{algorithmic}
produces
Ensure: x 6= 0 and n 0
7
3.10 Returning Values
The algorithmic environment offers a special statement for explicitly returning
values in algorithms. It has the syntax:
\RETURN <text>
For example,
\begin{algorithmic}
\RETURN $(x+y)/2$
\end{algorithmic}
produces
return ( x + y)/2
8
For example,
\begin{algorithmic}
\PRINT \texttt{Hello, World!}
\end{algorithmic}
produces
print Hello, World!
3.12 Comments
Comments may be inserted at most points in an algorithm using the form:
\COMMENT{<text>}
For example,
\begin{algorithmic}
\STATE do something \COMMENT{this is a comment}
\end{algorithmic}
produces
do something {this is a comment}
Because the mechanisms used to build the various algorithmic structures make it
difficult to use the above mechanism for placing comments at the end of the first
line of a construct, the commands \IF, \ELSIF, \ELSE, \WHILE, \FOR, \FORALL,
\REPEAT and \LOOP all take an optional argument which will be treated as a
comment to be placed at the end of the line on which they appear. For exam-
ple,
repeat {this is comment number one}
if condition one is met then {this is comment number two}
do something
else if condition two is met then {this is comment number three}
do something else
else {this is comment number four}
do nothing
end if
until hell freezes over
3.13 An Example
The following example demonstrates the use of the algorithmic environment
to describe a complete algorithm. The following input
\begin{algorithmic}
\REQUIRE $n \geq 0$
9
\ENSURE $y = x^n$
\STATE $y \leftarrow 1$
\STATE $X \leftarrow x$
\STATE $N \leftarrow n$
\WHILE{$N \neq 0$}
\IF{$N$ is even}
\STATE $X \leftarrow X \times X$
\STATE $N \leftarrow N / 2$
\ELSE[$N$ is odd]
\STATE $y \leftarrow y \times X$
\STATE $N \leftarrow N - 1$
\ENDIF
\ENDWHILE
\end{algorithmic}
will produce
Require: n 0
Ensure: y = x n
y1
Xx
Nn
while N 6= 0 do
if N is even then
X XX
N N/2
else {N is odd}
y yX
N N1
end if
end while
which is an algorithm for finding the value of a number taken to a non-negative
power.
10
05-08, a way to control the amount of indentation that is used by a given algo-
rithm.
The amount of indentation to be used is given by the command
\algsetup{indent=lenght}
where length is any valid length used by TEX. The default value of the indenta-
tion used by the algorithmic environment is 1 em (for backward compatibility
reasons), but a value of 2 em or more is recommended, depending on the pub-
lication. For example, the snippet
\algsetup{indent=2em}
\begin{algorithmic}[1]
\STATE $a \leftarrow 1$
\IF{$a$ is even}
\PRINT $a$ is even
\ELSE
\PRINT $a$ is odd
\end{algorithmic}
produces
1: a 1
2: if a is even then
3: print a is even
4: else
5: print a is odd
6: end if
while
\algsetup{indent=5em}
\begin{algorithmic}[1]
\STATE $a \leftarrow 1$
\IF{$a$ is even}
\PRINT $a$ is even
\ELSE
\PRINT $a$ is odd
\end{algorithmic}
would produce
1: a 1
2: if a is even then
3: print a is even
4: else
5: print a is odd
6: end if
The intended use of this option is to allow the author to omit the end (see
Section 3.14 for details) statements without loosing readability, by increasing the
amount of indentation to a suitable level.
11
3.14.2 Changing Line Numbering
As mentioned in Section 3 and illustrated in Section 3.14.1, algorithms already
provides you with the possibility of numbering lines.
Starting with the version released in 2005-07-05, you can now change two
aspects of line numbering: the size of the line numbers (which, by default, is
\footnotesize) and the delimiter used to separate the line number from the
code (which, by default, is :, i.e., a colon).
You can change the size of the line numbers using the command:
\algsetup{linenosize=size}
where size is any of the various commands provided by LATEX to change the size
of the font to be used. Among others, useful values are \tiny, \scriptsize,
\footnotesize and \small. Please see the complete list of sizes in your LATEX
documentation.
As another frequently requested feature, you can change the delimiter used
with the line numbers by issuing the command:
\algsetup{linenodelimiter=delimiter}
where delimiter is any well-formed string, including the empty string. With
this command, you can change the colon to a period (.) by issuing the command
\algsetup{linenodelimiter=.}
or even omit the delimiter, by specifying the empty string or a space (\ ), what-
ever seems best for your document.
As an example of such commands, the code produced by
\algsetup{
linenosize=\small,
linenodelimiter=.
}
\begin{algorithmic}[1]
\STATE $i \leftarrow 10$
\RETURN $i$
\end{algorithmic}
12
3.14.3 Customization
In order to facilitate the use of this package with foreign languages, all of the
words in the output are produced via redefinable macro commands. The default
definitions of these macros are:
\newcommand{\algorithmicrequire}{\textbf{Require:}}
\newcommand{\algorithmicensure}{\textbf{Ensure:}}
\newcommand{\algorithmicend}{\textbf{end}}
\newcommand{\algorithmicif}{\textbf{if}}
\newcommand{\algorithmicthen}{\textbf{then}}
\newcommand{\algorithmicelse}{\textbf{else}}
\newcommand{\algorithmicelsif}{\algorithmicelse\ \algorithmicif}
\newcommand{\algorithmicendif}{\algorithmicend\ \algorithmicif}
\newcommand{\algorithmicfor}{\textbf{for}}
\newcommand{\algorithmicforall}{\textbf{for all}}
\newcommand{\algorithmicdo}{\textbf{do}}
\newcommand{\algorithmicendfor}{\algorithmicend\ \algorithmicfor}
\newcommand{\algorithmicwhile}{\textbf{while}}
\newcommand{\algorithmicendwhile}{\algorithmicend\ \algorithmicwhile}
\newcommand{\algorithmicloop}{\textbf{loop}}
\newcommand{\algorithmicendloop}{\algorithmicend\ \algorithmicloop}
\newcommand{\algorithmicrepeat}{\textbf{repeat}}
\newcommand{\algorithmicuntil}{\textbf{until}}
\newcommand{\algorithmicprint}{\textbf{print}}
\newcommand{\algorithmicreturn}{\textbf{return}}
\newcommand{\algorithmictrue}{\textbf{true}}
\newcommand{\algorithmicfalse}{\textbf{false}}
If you would like to change the definition of these commands to another con-
tent, then you should use, in your own document, the standard LATEX command
renewcommand, with an usage like this:
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}
About the Way Comments Are Formatted The formatting of comments is im-
plemented via a single argument command macro which may also be redefined.
The default definition is
\newcommand{\algorithmiccomment}[1]{\{#1\}}
and another option that may be interesting for users familiar with C-like lan-
guages is to redefine the comments to be
\renewcommand{\algorithmiccomment}[1]{// #1}
13
Comments produced this way would be like this:
i i + 1 // Increments i
This second way to present comments may become the default in a future ver-
sion of this package.
4.2 An Example
To illustrate the use of the algorithm environment, the following text
\begin{algorithm}
\caption{Calculate $y = x^n$}
\label{alg1}
\begin{algorithmic}
\REQUIRE $n \geq 0 \vee x \neq 0$
\ENSURE $y = x^n$
\STATE $y \leftarrow 1$
\IF{$n < 0$}
\STATE $X \leftarrow 1 / x$
\STATE $N \leftarrow -n$
\ELSE
\STATE $X \leftarrow x$
\STATE $N \leftarrow n$
\ENDIF
\WHILE{$N \neq 0$}
\IF{$N$ is even}
\STATE $X \leftarrow X \times X$
\STATE $N \leftarrow N / 2$
\ELSE[$N$ is odd]
\STATE $y \leftarrow y \times X$
\STATE $N \leftarrow N - 1$
\ENDIF
\ENDWHILE
\end{algorithmic}
\end{algorithm}
2 This is the expected behaviour for floats in LAT X. If you dont care about having your algorithm
E
split between pages, then one option that you have is to ignore the algorithm environment.
14
produces Algorithm 1 which is a slightly modified version of the earlier algo-
rithm for determining the value of a number taken to an integer power. In this
case, provided the power may be negative provided the number is not zero.
Algorithm 1 Calculate y = x n
Require: n 0 x 6= 0
Ensure: y = x n
y1
if n < 0 then
X 1/x
N n
else
Xx
Nn
end if
while N 6= 0 do
if N is even then
X XX
N N/2
else // N is odd
y yX
N N1
end if
end while
4.3 Options
The appearance of the typeset algorithm may be changed by use of the options:
plain, boxed or ruled during the loading of the algorithm package. The default
option is ruled.
The numbering of algorithms can be influenced by providing the name of
the document component within which numbering should be recommenced.
The legal values for this option are: part, chapter, section, subsection,
subsubsection or nothing. The default value is nothing which causes algo-
rithms to be numbered sequentially throughout the document.
4.4 Customization
In order to facilitate the use of this package with foreign languages, methods
have been provided to facilitate the necessary modifications.
15
The title used in the caption within algorithm environment can be set by use
of the standard \floatname command which is provided as part of the float
package which was used to implement this package. For example,
\floatname{algorithm}{Procedure}
Warning You cant use the H positioning option together with the usual h (for
here), b (for bottom) etc. This is a limitation (as far as I know) of the float.sty
package.
16
Algorithm 2 Calculate y = x n
Require: n 0 x 6= 0
Ensure: y = x n
1: y 1
2: if n < 0 then
3: X 1/x
4: N n
5: else
6: Xx
7: Nn
8: end if
9: while N 6 = 0 do
10: if N is even then
11: X XX
12: N N/2
13: else
14: y yX
15: N N1
16: end if
17: end while
See that, in line 10, we deal with the case of N being even, while, in line 13,
we give treatment to the case of N being odd. The numbers you see on this
document were generated automatically from the source document.
in the preamble of your document, you can put, after \begin{document}, the
following snippet of code:
\renewcommand{\listofalgorithms}{\begingroup
\tocfile{List of Algorithms}{loa}
\endgroup}
\makeatletter
\let\l@algorithm\l@figure
\makeatother
17
7 Hints for Typesetting Algorithms
Here are some short hints on typesetting algorithms:
Dont overcomment your pseudo-code. If you feel that you need to com-
ment too much, then you are probably doing something wrong: you
should probably detail the inner workings of the algorithm in regular text
rather than in the pseudo-code;
Similarly, dont regard pseudo-code as a low-level programming lan-
guage: dont pollute your algorithms with punctuation marks like semi-
colons, which are necessary in C, C++ and Java, but not in pseudo-code.
Remember: your readers are not compilers;
Always document what the algorithm receives as an input and what it
returns as a solution. Dont care to say in the \REQUIRE or in the \ENSURE
commands how the algorithm does what it does. Put this in the regular
text of your book/paper/lecture notes;
If you feel that your pseudo-code is getting too big, just break it into sub-
algorithms, perhaps abstracting some tasks. Your readers will probably
thank you.
Of course, you should follow those hints with common sense. Well, anything
should be done with common sense.
18