[Tex/LaTex] Recursive algorithms with the »algorithms« package

algorithmsrecursion

I need to write a recursive algorithm, using the algorithms package.

I thought of writing something like this:

\begin{algorithmic}
\IF {$x=1}
    \RETURN 1
\ELSE
    \RETURN recurse$(x-1)$
\ENDIF
\end{algorithmic}

The problem here is that it's not obvious that the function "recurse" will call this very function (that is unnamed to start with) again. Is there a better way of doing it, besides stating in the text that "recurse" – well, recurses?

Best Answer

There doesn’t seem to be a way of defining procedures in algorithms but you can use an algorithm environment with an appropriate \caption that names your algorithm.

Personally, though, I would switch to the superior algorithmicx package that defines a \Procedure macro:

\begin{algorithm}
\Procedure{recurse}{$x$}
  \If{$x=1$}
    \State\Return{$1$}
  \Else
    \State\Return{\Call{recurse}{$x-1$}}
  \EndIf
\EndProcedure
\end{algorithm}