Introduction to Algorithms in LaTeX
When writing technical papers, computer science assignments, or documentation, presenting logic clearly is just as important as the text itself. While you could use a verbatim block or a code listing to show source code, pseudocode is often preferred for describing logic in a language-agnostic way.
LaTeX provides several powerful packages to typeset algorithms beautifully. These packages handle indentation, line numbering, and mathematical symbols automatically, ensuring your pseudocode looks professional and is easy to read. In this guide, we will focus on the two most popular approaches: the algpseudocode environment (part of the algorithmicx suite) and the algorithm2e package.
Choosing the Right Package
Before you start coding, you need to understand that typesetting an algorithm usually involves two distinct parts:
- The Wrapper (
algorithm): This treats the algorithm as a "float" (like a figure or table). It provides a caption, a frame, and an entry in the "List of Algorithms." - The Content (
algpseudocodeoralgorithm2e): This defines the actual syntax (commands likeif,while, andfor) used to write the logic.
For beginners, we recommend starting with the algpseudocode package because its syntax is very intuitive and mirrors standard programming logic.
Setting Up Your Document
To get started, you need to include the necessary packages in your LaTeX preamble. For the standard approach, add these lines:
\usepackage{algorithm}
\usepackage{algpseudocode}If you prefer the style of the other popular package, algorithm2e, you would use:
\usepackage[ruled,vlined]{algorithm2e}Note: Do not try to use
algpseudocodeandalgorithm2ein the same document unless you are an advanced user, as their commands often conflict with one another.
Writing Your First Algorithm with algpseudocode
The algpseudocode package uses a block-based syntax. Every structure (like an If or a For) must be explicitly started and ended.
Basic Syntax
\State: Used before every single line of command.\If{condition} ... \EndIf: For conditional logic.\For{condition} ... \EndFor: For loops.\Procedure{Name}{Arguments} ... \EndProcedure: To define a function.
Example 1: A Simple Loop
Here is how you would write a basic algorithm to calculate the sum of the first $n$ numbers.
\begin{algorithm}
\caption{Calculate Sum of N numbers}
\begin{algorithmic}[1] % The [1] enables line numbering
\Procedure{SumNumbers}{$n$}
\State $sum \gets 0$
\For{$i = 1$ \textbf{to} $n$}
\State $sum \gets sum + i$
\EndFor
\State \Return $sum$
\EndProcedure
\end{algorithmic}
\end{algorithm}Key features of this example:
- The
[1]after\begin{algorithmic}tells LaTeX to number every line. If you want to number every 5th line, use[5]. - We use math mode (between
$signs) for variables like$sum$to make them look consistent with mathematical notation. \getsis the standard LaTeX command for the assignment arrow ($\gets$).
Advanced Logic: Conditionals and Inputs
In real-world applications, algorithms require complex branching and descriptive inputs/outputs. algpseudocode provides specific commands for "Input" and "Output" through the \renewcommand feature, but most users simply use a custom state.
Example 2: The Euclidean Algorithm
This example demonstrates nested logic and how to format "Input" and "Output" sections.
\begin{algorithm}
\caption{Euclidean Algorithm (GCD)}
\label{alg:euclid}
\begin{algorithmic}[1]
\Require $a, b \geq 0$ \Comment{This acts as Input}
\Ensure $gcd(a, b)$ \Comment{This acts as Output}
\While{$b \neq 0$}
\State $r \gets a \bmod b$
\State $a \gets b$
\State $b \gets r$
\EndWhile
\State \Return $a$
\end{algorithmic}
\end{algorithm}Tip: Use the
\Comment{...}command to add explanatory notes to the right side of your lines. This is excellent for keeping your logic clean while explaining tricky parts to the reader.
The algorithm2e Alternative
While algpseudocode is very structured, many researchers prefer algorithm2e because it is more concise. It doesn't require a \State command for every line and uses a more "C-like" syntax.
Example 3: Sorting with algorithm2e
Note how the commands like \If, \For, and \KwData differ here.
\usepackage[ruled,vlined]{algorithm2e}
% Inside the document:
\begin{algorithm}
\DontPrintSemicolon
\KwData{A list of numbers $L$}
\KwResult{Sorted list $L$}
\Begin{
\For{$i=1$ \KwTo $length(L)$}{
\For{$j=i+1$ \KwTo $length(L)$}{
\If{$L[i] > L[j]$}{
swap($L[i], L[j]$)\;
}
}
}
\Return $L$\;
}
\caption{Bubble Sort Implementation}
\end{algorithm}What makes algorithm2e different?
\DontPrintSemicolon: Hides the semicolons at the end of lines in the final PDF.ruled, vlined: These package options create the horizontal lines at the top/bottom and vertical lines to indicate the scope of loops.\;: You must end every line with this command to indicate a line break.
Best Practices and Tips
To create the most readable algorithms, follow these industry standards:
- Use Math Mode for Variables: Always write
$x$instead of justx. This ensures that your variables look the same in your text as they do in your algorithm. - Label Everything: Add a
\label{alg:myname}inside the algorithm environment. You can then refer to it in your text usingAs seen in Algorithm~\ref{alg:myname}. - Keep it High-Level: Pseudocode is for humans, not compilers. Avoid language-specific syntax (like
i++) and use descriptive words (like $increment$ $i$) or mathematical notation. - Consistency is Key: Don't mix
algpseudocodeandalgorithm2estyles. Pick one and stick with it throughout your entire document. - Use the "List of Algorithms": If you have more than three algorithms, add
\listofalgorithmsat the beginning of your document (usually after the Table of Contents).
Common Mistakes to Avoid
- Forgetting
\State: Inalgpseudocode, if you forget\State, LaTeX will throw an error or your indentation will be completely broken. - Missing End Commands: Every
\Ifmust have a matching\EndIf. If you have nested loops, it is very easy to forget one, causing a "Missing }" error. - Overcrowding: If an algorithm is too long to fit on one page, consider breaking it into smaller sub-procedures. While there are ways to allow algorithms to break across pages (using the
algorithmicpackage), it usually makes the logic harder to follow. - Ignoring the Float Property: Remember that the
algorithmenvironment is a "float." LaTeX might move it to the next page to avoid leaving big gaps of white space. If you want to force it to stay "here," use the[H]specifier:\begin{algorithm}[H].
