Thomas Denney

Student and app developer

Typesetting algorithms with LaTeX

The algorithmicx package provides macros for typesetting algorithms that can include math or text, and code blocks are automatically indented. I don't particularly like the default style, however, as it redundantly includes a line for the end keyword for each block and doesn't allow for single line if statements, while loops, or for loops.

I therefore use the following:

\usepackage{algpseudocode}
\algtext*{EndWhile}
\algtext*{EndFor}
\algtext*{EndIf}
\algtext*{EndFunction}

\algnewcommand{\SIf}[1]{\State\algorithmicif\ #1\ \algorithmicthen}
\algnewcommand{\SElseIf}[1]{\State\algorithmicelse\ \algorithmicif\ #1\ \algorithmicthen}
\algnewcommand{\SElse}{\State\algorithmicelse\ }
\algnewcommand{\SWhile}[1]{\State\algorithmicwhile\ #1\ \algorithmicdo}
\algnewcommand{\SFor}[1]{\State\algorithmicfor\ #1\ \algorithmicdo}
\algnewcommand{\SForAll}[1]{\State\algorithmicforall\ #1\ \algorithmicdo}

This eliminates the end keywords and allow for the single line if statements, for example:

The above is typeset using:

\begin{algorithmic}
    \Function{Heapify}{$A, i$}
        \State $n := $ \Call{HeapSize}{$A$}
        \State $l := 2i + 1$
        \State $r := 2i + 2$
        \SIf{$l < n \wedge A[l] > A[i]$} $largest := i$
        \SElse $largest := i$
        \SIf{$r < n \wedge A[r] > A[largest]$} $largest := r$
        \If{$largest \neq i$}
            \State \Call{Swap}{$A[i], A[largest]$}
            \State \Call{Heapify}{$A, largest$}
        \EndIf
    \EndFunction
\end{algorithmic}