[Tex/LaTex] Place four algorithms (algorithm2e) in a subfigure and arrange them in two rows and two columns

algorithm2ehorizontal alignmentsubfloatsvertical alignment

I want to arrange four algorithms set with the algorithm2e package in two rows and two columns, as shown in the figure below. I've tried the subfigure package and have also read several related questions and answers, but have so far been unable to produce an output as shown below.

|------------------|       |-------------------|
|                  |       |                   |
|                  |       |                   |
|                  |       |                   |
|                  |       |                   |
|------------------|       |-------------------|
     (a) ...                       (b) ...

|------------------|       |-------------------|
|                  |       |                   |
|                  |       |                   |
|                  |       |                   |
|                  |       |                   |
|------------------|       |-------------------|
     (c) ...                       (d) ...

                  Figure 1: ...

Best Answer

You can use the subfigure environment from the subcaption package as follows.

screenshot

Note that the subfigure environment takes the same optional arguments that minipage does, so if you find yourself in a situation with different size code snippets you can use (for example) \begin{subfigure}[t]{.5\textwidth}...

\documentclass{article}
\usepackage{algorithm2e}
\usepackage{subcaption}

\newcommand{\myalgorithm}{%
\begin{algorithm}[H]
\SetAlgoLined
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\While{not at end of this document}{
read current\;
\eIf{understand}{
go to next section\;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\end{algorithm}}
\begin{document}

\begin{figure}
    \begin{subfigure}{.5\textwidth}
        \myalgorithm
        \caption{How to write algorithms}
    \end{subfigure}% need this comment symbol to avoid overfull hbox
    \begin{subfigure}{.5\textwidth}
        \myalgorithm
        \caption{How to write algorithms}
    \end{subfigure}\\
    \begin{subfigure}{.5\textwidth}
        \myalgorithm
        \caption{How to write algorithms}
    \end{subfigure}%
    \begin{subfigure}{.5\textwidth}
        \myalgorithm
        \caption{How to write algorithms}
    \end{subfigure}
\caption{Main caption}
\end{figure}


\end{document}