1. algorithm
and algorithmic
1.1 Adding packages
\usepackage{algorithm}
\usepackage{algorithmic}
1.2 Examples of algorithm
\begin{algorithm}[htb] % begin the algorithm environment
\caption{This is an algorithm} % name of the algorithm
\label{algorithm:alg1} % give it a label for referencing
\begin{algorithmic} % begin an algorithm
\REQUIRE something input % input of an algorithm
\STATE set some initial value
\FOR {condition for} % for loop begins
\STATE do something for
\ENDFOR % end for loop
\REPEAT % repeat loop
\STATE do something repeat
\UNTIL {condition repeat} % end repeat loop
\IF {condition if} % if condition begins
\STATE do something if
\ELSE
\STATE do something else
\ENDIF % end if
\WHILE {condition while} % while loop
\STATE do something while
\ENDWHILE % end while loop
\RETURN $S$ % return final result
\end{algorithmic} % end an algorithm
\end{algorithm} % end the algorithm environment
result
If you want to replace require
and return
with input
and output
, you need to add two lines
\renewcommand{\algorithmicrequire}{ \textbf{Input:}} %Use Input in the format of Algorithm
\renewcommand{\algorithmicreturn}{ \textbf{Output:}} %UseOutput in the format of Algorithm
2. algorithm2e
2.1 Adding package
\usepackage[linesnumbered,boxed]{algorithm2e}
2.2 Example
\begin{algorithm}
%\SetAlgoNoLine
\caption{This is an algorithm}
\KwIn {Input} %knote that Kw for key words
\KwData{data for alforithm: same as input}
\KwOut {Output}
\KwResult{same for output}
initialization\;
\For{for loop}{
do something for
}
\While{while loop}{
do something while\;
}
\If{condition if}{
do something if\;
}
\eIf{condition if else}{
do something if\;
}{
do other thing\;
}
\end{algorithm}
result
Note useful option for algorithm2e
% 1.boxed: to have algorithms enclosed in a box.
% 2.boxruled: surround algorithm by a box, puts caption above and add a line after caption.
% 3.ruled: to have algorithms with a line at the top and the bottom. Note that the caption is not
% centered under the algorithm anymore but is set at the beginning of the algorithm
% 4.algoruled: as above but with extra spaces after the rules
% 5.tworuled: tworuled acts like ruled but doesn’t put a line after the title.
% 6.plain: the default, with no feature.
% 1.algochapter: algorithms are numbered within chapter numbers.
% 2.algosection: (default) algorithms are numbered within section numbers.
% 3.algopart: algorithms are numbered within part numbers.
% 4.procnumbered: makes the procedure and function to be numbered as algorithm.
useful
http://tug.ctan.org/tex-archive/macros/latex/contrib/algorithm2e/doc/algorithm2e.pdf