\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 prefered by the professor} \State $i \gets 0$ \While {$i < n$ and $A[i] \neq E$} \If {A[i] $ = $ E} \State \Return \True \EndIf \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 occurences 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} \chapter{Motif} \begin{algorithm} \caption{Brute-force search of a motif in a sequence} \begin{algorithmic}[1] \Function{FindMotif}{S: Array(n), M: Array(m)} \Returns{list of position} \State $pos \gets $ empty list \State $i \gets 0$ \While {$i < n - m + 1$} \State $j \gets 0$ \While {$j < m$ and S[i+j] $ = $ M[j]} \State $j++$ \EndWhile \If {$j = m$} \State add $i$ to $pos$ \EndIf \State $i++$ \EndWhile \State \Return $pos$ \EndFunction \end{algorithmic} \end{algorithm} \begin{algorithm} \caption{Knuth-Morris-Pratt algorithm} \begin{algorithmic}[1] \Function{KMP\_Search}{S: Array(n), M: Array(m)} \Returns{Integer} \State $table \gets \Call{KMP\_Table}{M}$ \State $c \gets 0$ \Comment{Count the number of matches} \State $i \gets 0$ \State $j \gets 0$ \While {$i < n$} \If{$S[i] = M[i]$} \State $i \gets i + 1$ \State $j \gets j + 1$ \EndIf \If {$j = m$} \State $c \gets c + 1$ \State $j \gets table[j-1]$ \ElsIf {$j < n$ and $M[j] \neq S[i]$} \If {$j \neq 0$} \State $j \gets table[j-1]$ \Else \State $i \gets i + 1$ \EndIf \EndIf` \EndWhile \State \Return $c$ \EndFunction \Function{KMP\_Table}{M: Array(m)} \State \textbf{Returns} Array(m) \State $previous \gets 0$ \State $table \gets $ array of zeros of size m \For {$i = 0$; $i < m$; $i++$} \If {$M[i] = M[previous]$} \State $previous \gets previous + 1$ \State $table[i] \gets previous$ \State $i \gets i + 1$ \Else \If {$previous = 0$} \State $previous \gets table[previous - 1]$ \Else \State $table[i] \gets 0$ \State $i \gets 1$ \EndIf \EndIf \EndFor \EndFunction \end{algorithmic} \end{algorithm}