[Tex/LaTex] Setting caption/rule width in Algorithm2e algs

algorithm2ecaptionsindentationrules

Many of the algorithms I have with the algorithm2e package do not extend across the page width. If I use the package's boxruled or ruled options, the result is a box or rule that extends the pagewidth with a lot of whitespace on the right side.

I have changed the width of the algorithm itself using \setlength{\algomargin}{2in} but this does not have an effect on the width of the rules. The effect is to 'center' the algorithm code, but leave the environment itself the width of the page.

Is there a way to change that without having to squeeze it into a minipage?

UPDATE:
Minimal example:

\documentclass[10pt]{article}
\usepackage[ruled]{algorithm2e}
\begin{document}
\setlength{\algomargin}{2in}
\begin{algorithm}[t]
\caption{NaiveSelect}\label{algo:naive-option}
Some alg step \;
\end{algorithm}
\end{document}

Best Answer

Based on @lockstep answer, I've created a wrapper environment which allows the minipage width to be specified as an argument.

  %adds minipage to inside of algorithms
  \newlength{\tightalgowidth}
  \newlength{\tightalgoremainder}

  % uncomment to use centered floating algorithms
  \newenvironment{tightalgo}[2][]
  {
     \setlength{\tightalgowidth}{#2}
     \setlength{\tightalgoremainder}{\linewidth-\tightalgowidth}
     \begin{algorithm}[#1] }
  { \end{algorithm} }

  \makeatletter
  \patchcmd{\@algocf@start}{%
    \begin{lrbox}{\algocf@algobox}%
  }{%
    \rule{0.5\tightalgoremainder}{\z@}%
    \begin{lrbox}{\algocf@algobox}%
    \begin{minipage}{\tightalgowidth}%
  }{}{}
  \patchcmd{\@algocf@finish}{%
    \end{lrbox}%
  }{%
    \end{minipage}%
    \end{lrbox}%
  }{}{}
  \makeatother

Use it like this

  \begin{tightalgo}[ht]{0.5\linewidth}
  \caption{NaiveSelect}\label{algo:naive-option}
  Some alg step \;
  Some other \;
  \end{tightalgo}

For this result

enter image description here