Pseudocode Guide

In our study of algorithms, we’ll need to be able to communicate the instructions that compose our algorithms efficiently. As computer scientists, we tend to communicate these precise instructions through the use of programming languages. However, the major downside of using a programming language is that it requires the person you are trying to communicate with to understand the language’s syntax. To combat this, many algorithms are instead communicated via pseudocode. In the cs0500.cls class file we’ve already imported the algorithm and algpseudocodex packages! If you have any questions about this document, or pseudocode in general ask on EdStem or stop by TA hours!

The algorithm environment

The algorithm package provides the algorithm environment which gives you a fancy-looking block to place your algorithm(s) in. You can title the block using the \caption{...} command. You might also find it helpful to pass the optional H parameter to the environment to position the box in approximately the same place it appears relative to the source TEX code.

\begin{algorithm}[H]
  \caption{Very Important Algorithm!}
\end{algorithm}

the caption is rendered

The algorithmic environment

You’ll be writing your pseudocode in the algorithmic environment provided by algpseudocodex. The algorithmic environment has an optional parameter that labels every nth line number. For example, passing in [5] will label lines 5, 10, 15, etc. Note: It is not necessary to wrap an algorithmic environment in an algorithm environment. Here’s a list of helpful commands you might want to use in the algorithmic environment!

\begin{algorithm}[H]
\caption{‘‘Best’’ Sorting Algorithm}
\begin{algorithmic}[1]
\Require{An array, $A$}
\Ensure{The sorted array}
\Function{BubbleSort}{$A$}
  \State $n \gets$ length of $A$
  \State swapped $\gets$ true
  \chigh{yellow}{\While{swapped}
  \State swapped $\gets$ false
  \For{$i \in [1, n - 1]$}
    \If{\cstring{red!50}{
      $A[i - 1] > A[i]$}}
      \State\Call{Swap}
      {$A[i - 1], A[i]$}
      \State swapped $\gets$ true
    \EndIf
  \EndFor
\EndWhile}
\EndFunction
\end{algorithmic}
\end{algorithm}

the algorithhm is rendered

Tips for Writing Pseudocode

Now that you know how to write pseudocode, you’ll want to be sure you write clear, concise, and effective pseudocode! Nothing’s worse than spending forever on TEX’ing something, only to find out that you weren’t able to get your idea across. Here are a couple of tips!

If you have any feedback, you can fill out this anonymous Google Form!