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

64 lines
1.7 KiB
TeX
Raw Normal View History

2024-03-12 13:15:22 +01:00
\chapter{Back to basics}
\begin{algorithm}
2024-03-12 14:11:33 +01:00
\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}
2024-03-12 13:15:22 +01:00
\end{algorithm}
\begin{algorithm}
2024-03-12 14:11:33 +01:00
\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}
2024-03-12 13:15:22 +01:00
\end{algorithm}
\begin{algorithm}
2024-03-12 14:11:33 +01:00
\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}
2024-03-12 13:15:22 +01:00
\end{algorithm}
\begin{algorithm}
2024-03-12 14:11:33 +01:00
\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}
2024-03-12 13:15:22 +01:00
\end{algorithm}