The algorithms are set in a floating environment, whereas standalone
puts the contents in a box. This is incompatible.
However, if you give the algorithm the [H]
option, it will no longer be floating, so you can use it. It will no longer have the possibility to have a caption, unless you use the capt-of
or caption
package, but you probably will put the captions in your main document.
Note that it will not be possible to have the algorithms cropped to their minimal horizontal space, because the algorithm
package will put them in several layers of boxes, some of them with explicit width \hsize
. But I guess you want all of them to be the same width, and you can just set \hsize
to the desired width.
\documentclass[boxed,border=2pt]{standalone}
\usepackage{algorithm2e}
\begin{document}
\hsize=10cm
\setlength{\algomargin}{10pt}
\begin{algorithm}[H]
$x \gets 0$\;
\If{$x < 10$}{ $x \gets x + 1$\; }
\end{algorithm}
\end{document}

But if you need the algorithms in another document, framed and with figure captions, why don't you just put them there and use the figure,boxed
options?
\documentclass{article}
\usepackage[figure,boxed]{algorithm2e}
\begin{document}
\listoffigures
\section{Introduction}
This is my algorithm.
\begin{algorithm}
$x \gets 0$\;
\If{$x < 10$}{ $x \gets x + 1$\; }
\caption{This is the algorithm}
\end{algorithm}
This is the end of the document
\end{document}

This makes them float (it uses a real figure
environment, so they may end up at a different location, as all floats. You can prevent that by using \usepackage{float}
, and then \begin{algorithm}[H]
. However, this may cause undesired white space on the page if the algorithm doesn't fit.
You can also remove the figure
option; then the algorithm
environment has a [H]
option, that makes the algorithm non-floating. But then you must add a caption with the caption-of
or caption
package. In this case the caption will be placed outside the box, however.
\documentclass{article}
\usepackage[boxed]{algorithm2e}
\usepackage{capt-of}
\begin{document}
\listoffigures
\section{Introduction}
This is my algorithm.
\SetAlgoSkip{medskip}
\SetAlCapSkip{2ex}
\begin{algorithm}[H]
$x \gets 0$\;
\If{$x < 10$}{ $x \gets x + 1$\; }
\captionof{figure}{This is the algorithm}
\end{algorithm}
This is the end of the document
\end{document}
