20

I'm starting my experiment with LaTeX, i'm writing an article and all that I want is to embed an algorithm inside normal text, this is my code:

\documentclass{article}
\usepackage{algorithmic}
\begin{document}
\section{Lettura file .gpx} 
Lorem ipsum ...

\algsetup{indent=1.7em}
\begin{algorithm}
\caption{Alg capt}
\label{alg1}

\begin{algorithmic}[1]
... algorithm here...
\end{algorithmic}
\end{algorithm}
\end{document}

This is fully working but algorithmic uses a pagebreak automatically, how can I avoid this break and show the algorithm immediately after "lorem ipsum" part?

1
  • This post is also relevant. The answer suggests using \algstore and \algrestore for splitting the algorithm over several pages. Commented Mar 27 at 23:52

3 Answers 3

28

Here are some suggestions:

  • If you're adding your algorithm inside the algorithm float, then it will float according to the "float specifiers" given as the optional argument to the algorithm environment. For example

    \begin{algorithm}[ht]
      ...
    \end{algorithm}
    

To force the float to be less float-y, add ! to the float specifier. However, as suggested by the float package, this still remains a "suggestive specifier". Instead, the package provides the additional H float specifier which tells LaTeX to "PUT IT HERE!"

  • Use the algorithmicx package. It is very similar to algorithmic, but allows for more flexibility. Here's a short, yet complete, minimal example (from the algorithmicx package documentation).

  • If you wish to have the algorithm break across the page boundary, you have to set things up differently. I've incorporated a breakablealgorithm environment below.

enter image description here

\documentclass{article}

\usepackage{algorithm,algpseudocode}
\usepackage{lipsum}

\makeatletter
\newenvironment{breakablealgorithm}
  {% \begin{breakablealgorithm}
   \begin{center}
     \refstepcounter{algorithm}% New algorithm
     \hrule height.8pt depth0pt \kern2pt% \@fs@pre for \@fs@ruled
     \renewcommand{\caption}[2][\relax]{% Make a new \caption
       {\raggedright\textbf{\fname@algorithm~\thealgorithm} ##2\par}%
       \ifx\relax##1\relax % #1 is \relax
         \addcontentsline{loa}{algorithm}{\protect\numberline{\thealgorithm}##2}%
       \else % #1 is not \relax
         \addcontentsline{loa}{algorithm}{\protect\numberline{\thealgorithm}##1}%
       \fi
       \kern2pt\hrule\kern2pt
     }
  }{% \end{breakablealgorithm}
     \kern2pt\hrule\relax% \@fs@post for \@fs@ruled
   \end{center}
  }
\makeatother

\begin{document}

\listofalgorithms

\section{Some section}

\lipsum[1]

\begin{algorithm}[H]
  \caption{Euclid’s algorithm}\label{euclid}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d.\ of~$a$ and~$b$}
    \State $r \gets a \bmod b$
    \While{$r \neq 0$}\Comment{We have the answer if~$r$ is~$0$}
      \State $a \gets b$
      \State $b \gets r$
      \State $r \gets a \bmod b$
    \EndWhile
    \State \textbf{return} $b$\Comment{The g.c.d.\ is~$b$}
    \EndProcedure
  \end{algorithmic}
\end{algorithm}

\lipsum[2]

\begin{breakablealgorithm}
  \caption{Euclid’s algorithm}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d.\ of~$a$ and~$b$}
    \State $r \gets a \bmod b$
    \While{$r \neq 0$}\Comment{We have the answer if~$r$ is~$0$}
      \State $a \gets b$
      \State $b \gets r$
      \State $r \gets a \bmod b$
    \EndWhile
    \State \textbf{return} $b$\Comment{The g.c.d.\ is~$b$}
    \EndProcedure
  \end{algorithmic}
\end{breakablealgorithm}

\end{document}

The above redefinition of \caption assumes that it will be placed where it's located in the algorithm; specifically at the top. Rule definitions were taken from the float package's \@fs@ruled construction.

12
  • Werner's answer proposing begin{algorithm}[H] which is basically a float[H]? This means place the float 'here', however, it is still treated as a float and if Latex doesn't find enough text around it, the vertical spaces will be noticeable
    – isti_spl
    Commented Jul 6, 2013 at 18:34
  • 1
    @isti_spl: True. As such, it's not always advisable to use the [H] specifier. For more detail on the float placement algorithm, see How to influence the position of float environments like figure and table in LaTeX? and Keeping tables/figures close to where they are mentioned.
    – Werner
    Commented Jul 6, 2013 at 21:46
  • 2
    @Werner, wow this is so beautiful. Thank you so much.
    – CroCo
    Commented Feb 18, 2015 at 23:21
  • @Werner, hi, dude, your solution breakablealgorithm is great. However, i run into another problem. The label of the newly generate algorithm cannot be replaced by other language. For example, I need to replace Algorithm 1 with 算法 1 (In Chinese). I try to use command \floatname{algorithm}{算法}, but this only works for the default algorithm, not your breakablealgorithm. Any suggestions?
    – sunnycomes
    Commented Oct 22, 2020 at 6:38
  • 1
    @sunnycomes: Right. I've updated the code to use the appropriate float-based naming scheme.
    – Werner
    Commented Oct 22, 2020 at 20:48
15

If you don't want your algorithm to be treated as a floating object, then don't use the algorithm environment; you can still have a caption using the \captionof command from the caption package; using the appropriate style and format, this caption can have the same look and feel as those produced by the algorithm environment:

\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{caption}
\usepackage{lipsum}

\DeclareCaptionFormat{algor}{%
  \hrulefill\par\offinterlineskip\vskip1pt%
    \textbf{#1#2}#3\offinterlineskip\hrulefill}
\DeclareCaptionStyle{algori}{singlelinecheck=off,format=algor,labelsep=space}
\captionsetup[algorithm]{style=algori}

\begin{document}
\section{Lettura file .gpx} 
\lipsum*[1]
\begin{center}
  \captionof{algorithm}{Euclid’s algorithm}\label{euclid}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
    \State $r\gets a\bmod b$
    \While{$r\not=0$}\Comment{We have the answer if r is 0}
      \State $a\gets b$
      \State $b\gets r$
      \State $r\gets a\bmod b$
    \EndWhile
    \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
  \end{algorithmic}
\end{center}

\end{document}

enter image description here

3
  • 1
    Is there a way to insert a rule automatically at the end of the algorithm? I've try \rule[15pt]{\textwidth}{0.5pt} manually but it's so inconvenient and there will be a large gap between the rule and the following text. Thank you! @Gonzalo
    – Stan
    Commented Jan 8, 2013 at 8:48
  • @Stan, did you get a solution for the bottom line??
    – CroCo
    Commented Feb 18, 2015 at 22:30
  • Note: mixing this with actual algorithm floats leads to duplicated horizontal ruling.
    – Richard
    Commented Dec 24, 2015 at 3:56
2

Mine here is mainly based on Werner's amazing answer with one major fix: I grouped two top vertical lines and a caption as a page-unbreakable block using \parbox{}.

Below is the MME, compiled successfully with pdfTeX 3.14159265-2.6-1.40.20 (TeX Live 2019/Debian) on Kubuntu 20.04.2 LTS:

\documentclass{article}

\usepackage{algorithm, algpseudocode}
\usepackage{lipsum}

\makeatletter
\newenvironment{breakablealgorithm}
{
    \begin{center}
        \refstepcounter{algorithm}
        \renewcommand{\caption}[1]
        {
            \addcontentsline{loa}{algorithm}{\protect\numberline{\thealgorithm}##1}
            \parbox{\textwidth}
            % Makes a unbreakable block and can also be done by `minipage`.
            {
                \hrule height.8pt depth0pt \kern2pt
                {\raggedright\textbf{\fname@algorithm~\thealgorithm} ##1\par}
                \kern2pt\hrule\kern2pt
            }
        }
}
{
        \kern2pt\hrule\relax
    \end{center}
}
\makeatother

\begin{document}
    \listofalgorithms

    \section{Section One}
    \lipsum[1]
    \begin{breakablealgorithm}
        \caption{Euclid's algorithm}
        \begin{algorithmic}[1]
            \Procedure{Euclid}{$a, b$}
                \State $r \gets a \bmod b$
                \While{$r \not= 0$}
                    \State $a \gets b$
                    \State $b \gets r$
                    \State $r \gets a \bmod b$
                \EndWhile
                \State \textbf{return} $b$
            \EndProcedure
        \end{algorithmic}
    \end{breakablealgorithm}

    \lipsum[2]
    \begin{breakablealgorithm}
        \caption{Euclid's algorithm}
        \begin{algorithmic}[1]
            \Procedure{Euclid}{$a, b$}
                \State $r \gets a \bmod b$
                \While{$r \not= 0$}
                    \State $a \gets b$
                    \State $b \gets r$
                    \State $r \gets a \bmod b$
                \EndWhile
                \State \textbf{return} $b$
            \EndProcedure
        \end{algorithmic}
    \end{breakablealgorithm}
\end{document}

Some known issues for this code:

  1. The links to breakablealgorithm is pointed to slightly different positions compared to the normal algorithm enviroment;
  2. When \caption{} is not available (which is considered as a VERY BAD convention), breakablealgorithm will not draw two top horizontal lines since they come with \caption{};
  3. Figure/table floats may interrupt breakablealgorithm;
  4. The bottom horizontal line may be placed at the top of a new page.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .