latex之插入伪代码 [转]

时间:2021-11-03 18:47:21

常用的排版伪代码包有clrscode, algorithm, algorithmic, algorithmicx, algorithm2e


(1)clrscode
clrscode 是著名的算法教材 Introduction to Algorithms, 2nd ed. 的作者排版该书时自己制定的。由于我非常喜欢其排版,及写伪代码的风格是跟着这本书学的,所以摒弃了常用的算法排版宏包,而用这个。c l r s 分别是该书四个作者的姓的第一个字母,因此人们常以 clrs 指称该书。该包支持显示行号,加入注释,能够每行 label 及引用。

以下是 Insertion-Sort 算法的 code

 1 \begin{codebox}
2 \Procname{$\proc{Insertion-Sort(A)}$}
3 \li \For $j \gets 2$ \To $\id{length}[A]$ \label{li:for}
4 \li \Do $\id{key} \gets A[j]$ \label{li:for-begin}
5 \li \Comment Insert $A[j]$ into the sorted sequence $A[1 \twodots j-1]$.
6 \li $i \gets j-1$
7 \li \While $i>0$ and $A[i]>\id{key}$ \label{li:while}
8 \li \Do $A[i+1] \gets A[i]$ \label{li:while-begin}
9 \li $i \gets i-1$ \label{li:while-end}
10 \End
11 \li $A[i+1] \gets \id{key}$ \label{li:for-end}
12 \End
13 \end{codebox}

 

(2)algorithmic

 1 \begin{algorithmic}
2 \REQUIRE $n \geq 0$
3 \ENSURE $y = x^n$
4 \STATE $y \Leftarrow 1$
5 \STATE $X \Leftarrow x$
6 \STATE $N \Leftarrow n$
7 \WHILE{$N \neq 0$}
8 \IF{$N$ is even}
9 \STATE $X \Leftarrow X \times X$
10 \STATE $N \Leftarrow N / 2$
11 \ELSE[$N$ is odd]
12 \STATE $y \Leftarrow y \times X$
13 \STATE $N \Leftarrow N - 1$
14 \ENDIF
15 \ENDWHILE
16 \end{algorithmic}

latex之插入伪代码 [转]

 

(3)algorithm
latex之插入伪代码 [转]

 

[转] http://blog.sina.com.cn/s/blog_6a4b2dea0100m7gf.html

-------------------------------------

 1 \ usepackage { algorithm } 
2 \ usepackage { algorithmic }
3
4
5
6 \begin { algorithm }
7 \ caption { Calculate$y = x^n$ }
8 \begin { algorithmic }
9 \REQUIRE $n\geq 0\vee x\neq 0$
10 \ENSURE $y = x^n$
11 \STATE $y\leftarrow 1$
12 \IF { $n < 0$ }
13 \STATE $X\leftarrow 1 / x$
14 \STATE $N\leftarrow -n$
15 \ELSE
16 \STATE $X\leftarrow x$
17 \STATE $N\leftarrow n$
18 \ENDIF
19 \WHILE { $N\neq 0$ }
20 \IF { $N$ is even }
21 \STATE $X\leftarrow X\times X$
22 \STATE $N\leftarrow N / 2$
23 \ELSE [ $N$ is odd ]
24 \STATE $y\leftarrow y\times X$
25 \STATE $N\leftarrow N - 1$
26 \ENDIF
27 \ENDWHILE
28 \end { algorithmic }
29 \end { algorithm } Upload

 

latex之插入伪代码 [转]

Here are useful commands:

Single line statements 

\STATE <text>

If-statements 

\IF {<condition> } <text> \ENDIF 

\IF { <condition> } <text> \ELSE <text> \ENDIF 
\IF { <condition> } <text> \ELSIF { <condition> } <text> \ELSE<text> \ENDIF 

For-loops

There are two forms

\FOR { <condition> } <text> \ENDFOR 
\FORALL { <condition> } <text> \ENDFOR 

While-loops 

\WHILE {<condition> } <text> \ENDWHILE

Repeat until condition 

\REPEAT<text> \UNTIL { <condition> }

Infinite loops 

\LOOP <text>\ENDLOOP

Precondition 

\REQUIRE <text>

Postcondition 

\ENSURE<text>

Returning variables 

\RETURN <text>

Printing variables 

\PRINT<text>

 

Note: Due to a bug, the algorithmic package is not compatible with hyperref.

 

[转]http://www.math-linux.com/spip.php?article129