sequence-algorithms/content/chapters/part1/0.tex

59 lines
1.4 KiB
TeX
Executable File

\chapter{Back to basics}
\begin{algorithm}
\caption{Search an element in an array}
\begin{algorithmic}[1]
\Function{Search}{$A$: Array($n$), $E$: element}
\For {($i = 0$; $i < n$; $i++$)}
\If {$A[i] = E$}
\State \Return \True
\EndIf
\EndFor
\State \Return \False
\EndFunction
\end{algorithmic}
\end{algorithm}
\begin{algorithm}
\caption{Search an element in an array using a while loop}
\begin{algorithmic}[1]
\Function{Search}{$A$: Array($n$), $E$: element}
\State $i \gets 0$
\While {$i < n$}
\If {$A[i] = E$}
\State \Return \True
\EndIf
\State $i \gets i + 1$
\EndWhile
\State
\Return
\False
\EndFunction
\end{algorithmic}
\end{algorithm}
\begin{algorithm}
\caption{Search an element in an array using a while loop (bis)}
\begin{algorithmic}[1]
\Function{Search}{$A$: Array($n$), $E$: element}
% \Comment{Version ``preffered" by the professor}
\State $i \gets 0$
\While {$i < n$ and $A[i] \neq E$}
\State $i \gets i + 1$
\EndWhile
\If {$i = n$}
\State
\Return \False \Else \State \Return \True \EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}
\begin{algorithm}
\caption{Count the occurrences of an element in an array}
\begin{algorithmic}[1]
\Function{Search}{$A$: Array($n$), $E$: element} \State $c \gets 0$
\For{($i = 0$; $i < n$; $i++$)} \If {A[i] $ = $ E} \State $c \gets c + 1$ \EndIf
\EndFor \State \Return $c$ \EndFunction
\end{algorithmic}
\end{algorithm}