Latex排版Algorithm之algorithmic,algorithmicx,algorithm2e

本文介绍了LaTeX中常用的两种算法排版环境algorithmicx和algorithm2e,指出algorithmic较旧且不常用。通过示例展示了algorithmicx和algorithm2e的使用方法,包括如何定义Input和Output。并提供了修改环境实现特定格式的代码片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • algorithmic是第一代算法排版环境
  • algorithmicx是第二代算法排版环境
  • algorithm2e是第三版算法排版环境

以上三种算法排版环境中algorithmic比较老了,现在用的较多的是algorithmicx和algorithm2e排版环境。并且这三种排版环境不能混用。我个人比较喜欢algorithm2e的排版样式。具体参考这个链接

一般latex模板文件夹有一个cls的文件,里面会说明支持的Algorithm排版环境,用Notepad++打开搜索algorithm会找到类似于“\usepackage{algorithm, algorithmicx, algpseudocode}”的代码,定义了该latex模板支持的排版环境。我用的latex模板就不支持algorithm2e,只能使用algorithmicx。

  • algorithmicx实例
\documentclass{article}
\title{Test title}
\author{ Mary\thanks{E-mail:*****@***.com}
	\and Ted\thanks{Corresponding author}
	\and Louis}
\date{\today}
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}[h] 
	\caption{Conjugate Gradient Algorithm with Dynamic Step-Size Control} 
	\label{alg::conjugateGradient} 
	\begin{algorithmic}[1] 
		\Require 
		$f(x)$: objective funtion; 
		$x_0$: initial solution; 
		$s$: step size; 
		\Ensure 
		optimal $x^{*}$ 
		\State initial $g_0=0$ and $d_0=0$; 
		\Repeat 
		\State compute gradient directions $g_k=\bigtriangledown f(x_k)$; 
		\State compute Polak-Ribiere parameter $\beta_k=\frac{g_k^{T}(g_k-g_{k-1})}{\parallel g_{k-1} \parallel^{2}}$; 
		\State compute the conjugate directions $d_k=-g_k+\beta_k d_{k-1}$; 
		\State compute the step size $\alpha_k=s/\parallel d_k \parallel_{2}$; 
		\Until{($f(x_k)>f(x_{k-1})$)} 
	\end{algorithmic} 
\end{algorithm}
\end{document}

效果如下:
在这里插入图片描述
想要将RequireEnsure替换为InputOutput需要在document开始前添加如下两行代码:

\renewcommand{\algorithmicrequire}{\textbf{Input:}} % Use Input in the format of Algorithm
\renewcommand{\algorithmicensure}{\textbf{Output:}} % Use Output in the format of Algorithm

  • algorithmi2e实例
\documentclass{article}
\title{Test title}
\author{ Mary\thanks{E-mail:*****@***.com}
	\and Ted\thanks{Corresponding author}
	\and Louis}
\date{\today}
\usepackage[ruled]{algorithm2e} %ruled控制布局格式
\begin{document}
\begin{algorithm} 
	%\SetAlgoNoLine %控制有无竖线
	\caption{identifyRowContext} 
	\KwIn{$r_i$, $Backgrd(T_i)$=${T_1,T_2,\ldots ,T_n}$ and similarity threshold $\theta_r$} 
	\KwOut{$con(r_i)$} 
	$con(r_i)= \Phi$\; 
	\For{$j=1;j \le n;j \ne i$} 
	{ 
		float $maxSim=0$\; 
		$r^{maxSim}=null$\; 
		\While{not end of $T_j$} 
		{ 
			compute Jaro($r_i,r_m$)($r_m\in T_j$)\; 
			\If{$(Jaro(r_i,r_m) \ge \theta_r)\wedge (Jaro(r_i,r_m)\ge r^{maxSim})$} 
			{ 
				replace $r^{maxSim}$ with $r_m$\; 
			} 
		} 
		$con(r_i)=con(r_i)\cup {r^{maxSim}}$\; 
	} 
	return $con(r_i)$\; 
\end{algorithm}
\end{document}

效果如下所示:
在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值