12

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?

3
  • In your original question it said "algorithmic package". Did you mean algorithmicx or algorithms (or maybe even algorithm2e)? Commented Feb 22, 2011 at 8: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. Commented Mar 2, 2011 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. Commented Mar 2, 2011 at 11:55

1 Answer 1

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}
2
  • It may be that the OP is already using algorithmicx; see my comment to the question. (Doesn't matter too much for your answer :-)) Commented Feb 22, 2011 at 8: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. Commented Mar 2, 2011 at 11:52

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.