5

What is the best way to center an algorithm2e environment horizontally on a page? Is it \centering just like with figures, or rather an enclosing \begin{center} ... \end{center} or is it even necessary to use a minipage?

Thanks in advance!

  • It depends on the environment. Anything with a \caption in it, or a list environment, needs to be inside a minipage. There are other ways to center, such as \hfil or \leftskip and \rightskip. – John Kormylo Mar 21 '17 at 15:31

1 Answers1

5

The default behaviour of algorithm2e's algorithm environment is to be full-width spanning across the entire text block width. One could say that it's necessarily centred then. If you're interested in a less-than-\textwidth centering, then you need to be a bit more creative:

Set your algorithm inside a minipage of pre-specified width inside another float (like figure). Make sure you use the [H] float specifier to stop the algorithm from floating. The floating behaviour will be managed by figure. Then use the regular \centering. algorithm2e provides no natural way to adjust the width. With \SetCustomAlgoRuledWidth{width} you can adjust the width.

enter image description here

\documentclass{article}

\usepackage[ruled,linesnumbered]{algorithm2e}

\begin{document}

\begin{algorithm}[ht]
  \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\;
    }
  }
  \caption{How to write algorithms}
\end{algorithm}

\begin{figure}[ht]
  \centering
  \begin{minipage}{.7\linewidth}
    \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\;
        }
      }
      \caption{How to write algorithms}
    \end{algorithm}
  \end{minipage}
\end{figure}

\end{document}

Note that this approach places the same construction in different floats and therefore may cause incorrect number ordering of algorithms if both the above techniques are used close to one another (like Algorithm 5 appearing before Algorithm 4, say). One would have to play around with the placement of the code in order to achieve the appropriate ordering in such cases.

Stefan Pinnow
  • 29,535
Werner
  • 603,163