我编写了此代码来制定合并两个数组的算法,但是出现了错误。
\begin{algorithm}[t]
\caption{Serial Merge}
\label{alg:insert}
\begin{algorithmic}[1]
\Require Two sorted arrays $A$ and $B$
\Ensure Sorted Array $C$
\State $lA \leftarrow length(A)$
\State $lB \leftarrow length(B)$
\State $x \leftarrow 0$
\State $y \leftarrow 0$
\State $z \leftarrow 0$
\While { $x \neq lA$ and $y \neq lB$ }
\If { $A[x] < $B[y]$}
\State $C[z++] \leftarrow A[x++]$
\Else
\State $C[z++] \leftarrow B[y++]$
\EndIf
\EndWhile
\While { $x \neq lA$ }
\State $C[z++] \leftarrow A[x++]$
\EndWhile
\While { $y \neq lB$ }
\State $C[z++] \leftarrow B[y++]$
\EndWhile
\end{algorithmic}
\end{algorithm}
错误:
! LaTeX Error: Command \item invalid in math mode.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.15 \State
$C[z++] \leftarrow A[x++]$
?
如果我删除周围的 if else 语句,它就会起作用。我做错了什么?
答案1
在行中
\If { $A[x] < $B[y]$}
$
“B” 之前有一个虚假字符;只需将其删除:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}%[t]
\caption{Serial Merge}
\label{alg:insert}
\begin{algorithmic}[1]
\Require Two sorted arrays $A$ and $B$
\Ensure Sorted Array $C$
\State $lA \leftarrow length(A)$
\State $lB \leftarrow length(B)$
\State $x \leftarrow 0$
\State $y \leftarrow 0$
\State $z \leftarrow 0$
%
\While { $x \neq lA$ and $y \neq lB$ }
\If { $A[x] < B[y]$}
\State $C[z++] \leftarrow A[x++]$
\Else
\State $C[z++] \leftarrow B[y++]$
\EndIf
\EndWhile
%
\While { $x \neq lA$ }
\State $C[z++] \leftarrow A[x++]$
\EndWhile
%
\While { $y \neq lB$ }
\State $C[z++] \leftarrow B[y++]$
\EndWhile
\end{algorithmic}
\end{algorithm}
\end{document}