15

I use algorithm/algorithmic packages to write some pseudocode. The width of the box spans across the entire page and I was wondering if there is any way to constrain it (since the actual code doesn't exceed the mid of the page). Practically, I want to wrap text around my pseudocode.

ps: I tried wrapfig package, but I had some problems. Would be also helpful if anyone could verify whether this approach works.

Any ideas ?

2
  • Don't forget about TeX - LaTeX; LaTeX is odd enough that you'd be better served asking in a community dedicated to LaTeX and TeX. (I've flagged for moderator attention to migrate, but in case the mod doesn't migrate -- we do have LaTeX questions here, in any case -- just know it's available.)
    – sarnold
    Dec 12 '11 at 8:27
  • Welcome to TeX.sx! Your question was migrated here from another StackExchange site. Please register on this site, too, and make sure that both accounts are associated with each other, otherwise you won't be able to comment on or accept answers or edit your question. :) Dec 12 '11 at 10:28
18

You can put the algorithm inside of a minipage, put that inside of the wrapfigure, and it should work like a charm.

\documentclass{article}
\usepackage{algorithmic}
\usepackage{algorithm}
\usepackage{wrapfig}
\usepackage{lipsum}
\begin{document}
  \lipsum[1]
  \begin{wrapfigure}{L}{0.5\textwidth}
    \begin{minipage}{0.5\textwidth}
      \begin{algorithm}[H]
        \caption{assignment algorithm}
        \begin{algorithmic}
          \STATE i $\leftarrow$ j
        \end{algorithmic}
      \end{algorithm}
    \end{minipage}
  \end{wrapfigure}
  \lipsum
\end{document}

And the result:

Wrapped algorithm

You might want to tweak the alignment modifier on the minipage to get vertical alignment to work out a little better. Alternatively, you can play with the optionial lineheight of wrapfigure.

3
  • Could one modify this to work with Algorithm2e?
    – JeremyKun
    May 7 '15 at 17:39
  • @JeremyKun A bit late, but for me it works with Algorithm2e Sep 6 '20 at 19:10
  • Worked for me, but I needed just \begin{minipage} rather than \begin{minipage}{0.5\textwidth}, or else the width was 0.5*0.5 the page width, rather than just 0.5. Aug 31 at 19:14
4

You can achieve the same result using algorithm2e package and without minipage.

\documentclass{article}
\usepackage{wrapfig}
\usepackage{lipsum}
\usepackage[ruled]{algorithm2e}
\begin{document}
  \lipsum[1]
  \begin{wrapfigure}[6]{L}{0.5\textwidth} %<-- Wrapfigure covers 6 lines
      \begin{algorithm}[H]                %<-- Remove float environment
        \SetCustomAlgoRuledWidth{0.45\textwidth}  %<-- For aesthetics  
        \caption{assignment algorithm}
           i $\leftarrow$ j
      \end{algorithm}
  \end{wrapfigure}
  \lipsum
\end{document}

Wrapped pseudo using algorithm2e

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy