2

I want to write the following algorithm in LaTeX.

image of algorithmn

The code I used is as follows:

\documentclass{article}
\usepackage{algorithm}
\usepackage{algorithmic}
%\usepackage{algpseudocode}
%\algtext*{EndIf}
\begin{document}
\begin{algorithm}
\caption{Left-rotate $(T,x)$}
\begin{algorithmic}
\STATE $y \gets \mathrm{right}[x]$
\STATE $ \mathrm{right}[x] \gets \mathrm{left}[y]$
\IF {$ \mathrm{left}[y] \neq \mathrm{NIL} $}
\STATE $ p[\mathrm{left}[y]] \gets x $
\ENDIF
\IF {$ p[x]=\mathrm{NIL} $}
\STATE $ \mathrm{root}[T] \gets y $
\ELSIF {$ x=\mathrm{left}[p[x]] $}
\STATE $ \mathrm{left}[p[x]] \gets y $
\ELSE 
\STATE $ \mathrm{right}[p[x]] \gets y $
\ENDIF
\STATE $ \mathrm{left}[y] \gets x $
\STATE $ p[x] \gets x $
\end{algorithmic}
\end{algorithm}
\end{document}

I have already tried all the solutions on this platform but unfortunately, none worked. The output generated is the following:

result

I do not want the \ENDIF, it would be nice if then can be on the line below the one with \IF, and the nesting should be according to the first image. Please help me out.

1 Answer 1

3

Simply add package option noend to algorithmic:

\usepackage[noend]{algorithmic}

With the following complete code

\documentclass{article}
\usepackage{algorithm}
\usepackage[noend]{algorithmic}
%\usepackage{algpseudocode}
%\algtext*{EndIf}
\begin{document}
\begin{algorithm}
\caption{Left-rotate $(T,x)$}
\begin{algorithmic}
\STATE $y \gets \mathrm{right}[x]$
\STATE $ \mathrm{right}[x] \gets \mathrm{left}[y]$
\IF {$ \mathrm{left}[y] \neq \mathrm{NIL} $}
  \STATE $ p[\mathrm{left}[y]] \gets x $
\ENDIF
\IF {$ p[x]=\mathrm{NIL} $}
  \STATE $ \mathrm{root}[T] \gets y $
\ELSIF {$ x=\mathrm{left}[p[x]] $}
    \STATE $ \mathrm{left}[p[x]] \gets y $
  \ELSE 
    \STATE $ \mathrm{right}[p[x]] \gets y $
\ENDIF
\STATE $ \mathrm{left}[y] \gets x $
\STATE $ p[x] \gets x $
\end{algorithmic}
\end{algorithm}
\end{document}

you get the result:

result

I personaly would prefer the version with end marks, the algorithm is better readable ...

2
  • Thank you. Can you also have the indentation as required (for \ELSE after the \ELSIF)?
    – user473334
    Apr 28, 2019 at 20:16
  • And can I also send 'then' to the next line?
    – user473334
    Apr 28, 2019 at 20:17

You must log in to answer this question.

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