11

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?

Sewi
  • 113
  • In your original question it said "algorithmic package". Did you mean algorithmicx or algorithms (or maybe even algorithm2e)? – Hendrik Vogt Feb 22 '11 at 08:08
  • Sorry for my detailed response - the packages I import are \usepackage{algorithm} and \usepackage{algorithmic} . When I first wrote the algorithms, I did not know which package to used, and a Google search suggested that these were the packages usually used - hence I formatted my algorithms with these in mind. I can re-write them for a new package, of course, if it offers a solution to my problem. – Sewi Mar 02 '11 at 11:48
  • That should read "delayed" instead of "detailed". I will use the algorithmicx package as Konrad suggested - being able to encapsulate the algorithm in a procedure should be the least ambiguous way of describing recursion. – Sewi Mar 02 '11 at 11:55

1 Answers1

11

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}
Konrad Rudolph
  • 39,394
  • 22
  • 107
  • 160
  • It may be that the OP is already using algorithmicx; see my comment to the question. (Doesn't matter too much for your answer :-)) – Hendrik Vogt Feb 22 '11 at 08:09
  • A procedure macro was exactly what I was hoping for. The syntax of the algorithmicx package seems quite similar to the algorithmic package, so there should be little overhead rewriting the algorithms. Thank you, Konrad. – Sewi Mar 02 '11 at 11:52