I'm trying to put two algorithm listings side by side within an figure environment, to refer them as sub-figures. I tried many, many options, but none has worked so far.
The "obvious" approach, putting subfloats in the figure, as shown below, throws the infamous error "! LaTeX Error: Something's wrong--perhaps a missing \item."
NEW: TikZ book now 40% off at Amazon.com for a short time.
And: Currently, Packt sells ebooks for $4.99 each if you buy 5 of their over 1000 ebooks. If you choose only a single one, $9.99. How about combining 3 LaTeX books with Python, gnuplot, mathplotlib, Matlab, ChatGPT or other AI books? Epub and PDF. Bundle (3 books, add more for higher discount): https://packt.link/MDH5p
one possibility would be to use minipages and the \captionof command provided by the caption package (see Remarks below); the following example illustrates this approach:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{caption}
\begin{document}
\noindent\begin{minipage}{\textwidth}
\centering
\begin{minipage}{.45\textwidth}
\centering
\captionof{algorithm}{test algorithm 1}
\label{alg:alg1}
\begin{algorithmic}
\WHILE{$N \neq 0$}
\IF{$N$ is even}
\STATE $X \Leftarrow X \times X$
\STATE $N \Leftarrow N / 2$
\ENDIF
\ENDWHILE
\end{algorithmic}
\end{minipage}
\begin{minipage}{.45\textwidth}
\centering
\captionof{algorithm}{test algorithm 2}
\label{alg:alg2}
\begin{algorithmic}
\WHILE{$N \neq 0$}
\IF{$N$ is even}
\STATE $X \Leftarrow X \times X$
\STATE $N \Leftarrow N / 2$
\ENDIF
\ENDWHILE
\end{algorithmic}
\end{minipage}
\captionof{figure}{Two algorithms side by side}
\label{fig:twoalg}
\end{minipage}
Figure~\ref{fig:twoalg} shows two algorithms side by side: they can be referenced as algorithm~\ref{alg:alg1} and algorithm~\ref{alg:alg2}...
\end{document}
Remarks: 1) Make sure that you have a recent version (3.1x) of the package installed in your system.
2) Please take into account that since minipages were used this is not a floating object.
NEW: TikZ book now 40% off at Amazon.com for a short time.
And: Currently, Packt sells ebooks for $4.99 each if you buy 5 of their over 1000 ebooks. If you choose only a single one, $9.99. How about combining 3 LaTeX books with Python, gnuplot, mathplotlib, Matlab, ChatGPT or other AI books? Epub and PDF. Bundle (3 books, add more for higher discount): https://packt.link/MDH5p