文章目录
展开
这几天在用 LaTeX 写一些东西,需要用到一个比较新的算法包,algorithm2e,因为之前没用过,所以花些时间了解了一下。感觉比 algorithmc 用起来方便点,更符合代码书写习惯,也不用写那么多麻烦的 \STATE 之类的无意义状态语。下面了解一下这个 algorithm2e 的一些简明的用法,也算是做个记录。
一、Algorithm2e 基本语法
使用之前当然需要先引入:
\usepackage[options ]{algorithm2e}
具体的 options 可以查看下面参考文献 2 的第七章,比如:
\usepackage[ruled,linesnumbered]{algorithm2e}
其中:
ruled是让标题显示在上面,否则算法的标题则在下面。linesnumbered让算法中显示行号。- 还可以添加
boxed, 让算法排版时插入在一个盒子里。
基本语法:

更多说明:
- 如果你不想让你的伪代码叫做 ‘Algorithm 编号’, 可以使用
\renewcommand{\algorithmcfname}{算法名}命令来修改。 - 除了\If, \Else, \ElseIf之外,还有\uIf, \lIf, \uElse, \lElse, \uElseIf, \lElseIf等命令,他们的区别在于
- \If, \Else, \ElseIf都是会以end结尾
- \uIf, \uElse, \uElseIf, 是不以end结尾的块级元素
- \lIf, \lElse, \lElseIf 是不以end为结尾的行内元素
- 在If-else结构中,\eIf 自带else(即 if 和 else 共用一个 end),而只是用 \If 和 \Else 的话则会多出一个end给Else。
此外,Algorithm2e 本身不支持 Do-While 结构(支持的是 While-Do),需要自行定义。不过自行定义并不难,因为宏包中内置了 Repeat-Until 结构,在 Algorithm2e 中是“宏指令(Repeat macros)”的一种
自定义宏指令
\SetKwRepeat{Do}{do}{while}
定义完之后,就可以在伪代码块中使用如下命令调用
\Do{<结束条件>}{<执行命令>}
二、Algorithm2e 使用示例
简单示例:
\begin{algorithm}[H]
\SetAlgoLined
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\While{not at end of this document}{
read current\;
\eIf{understand}{
go to next section\;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\caption{How to write algorithms}
\end{algorithm}
效果如下:

更多示例:
下面的例子更完整一些:
\begin{algorithm}
\SetKwData{Left}{left}\SetKwData{This}{this}\SetKwData{Up}{up}
\SetKwFunction{Union}{Union}\SetKwFunction{FindCompress}{FindCompress}
\SetKwInOut{Input}{input}\SetKwInOut{Output}{output}
\Input{A bitmap $Im$ of size $w\times l$}
\Output{A partition of the bitmap}
\BlankLine
\emph{special treatment of the first line}\;
\For{$i\leftarrow 2$ \KwTo $l$}{
\emph{special treatment of the first element of line $i$}\;
\For{$j\leftarrow 2$ \KwTo $w$}{\label{forins}
\Left$\leftarrow$ \FindCompress{$Im[i,j-1]$}\;
\Up$\leftarrow$ \FindCompress{$Im[i-1,]$}\;
\This$\leftarrow$ \FindCompress{$Im[i,j]$}\;
\If(\tcp*[h]{O(\Left,\This)==1}){\Left compatible with \This}{\label{lt}
\lIf{\Left $<$ \This}{\Union{\Left,\This}}
\lElse{\Union{\This,\Left}}
}
\If(\tcp*[f]{O(\Up,\This)==1}){\Up compatible with \This}{\label{ut}
\lIf{\Up $<$ \This}{\Union{\Up,\This}}
\tcp{\This is put under \Up to keep tree as flat as possible}\label{cmt}
\lElse{\Union{\This,\Up}}\tcp*[h]{\This linked to \Up}\label{lelse}
}
}
\lForEach{element $e$ of the line $i$}{\FindCompress{p}}
}
\caption{disjoint decomposition}\label{algo_disjdecomp}
\end{algorithm}
效果如下:

至此我认为基本的用法都有了,需要更完整的可以直接查看下面的参考文献 2 里面的更多介绍。
参考文献:
- https://www.ctan.org/pkg/algorithm2e
- https://mirrors.ustc.edu.cn/CTAN/macros/latex/contrib/algorithm2e/doc/algorithm2e.pdf
- https://zhuanlan.zhihu.com/p/166418214