Sorted Array - Question 5 Answers

5.a

\begin{algorithm}
\caption{Find the minimum value in the supplied array}
\begin{algorithmic}
\REQUIRE A = randomly ordered array
\OUTPUT $\min{A}$
\FUNCTION{min}{A}
    \STATE $m \gets \infty$
    \FOR{$i \in A$}
        \IF{$i \lt m$}
            \STATE $m \gets i$
        \ENDIF
    \ENDFOR
    \RETURN{$m$}
\ENDFUNCTION
\end{algorithmic}
\end{algorithm}

5.b

\begin{algorithm}
\caption{Find the successor of the specified item in the supplied array}
\begin{algorithmic}
\REQUIRE A = randomly ordered array
\REQUIRE item = reference item
\OUTPUT item immediately following item
\FUNCTION{successor}{A, item}
    \STATE $s \gets \infty$
    \FOR{$i \in A$}
        \IF{$i \gt \text{item}$ and $i \lt s$}
            \STATE $s \gets i$
        \ENDIF
    \ENDFOR
    \RETURN{s}
\ENDFUNCTION
\end{algorithmic}
\end{algorithm}

5.c

\begin{algorithm}
\caption{Find the rank of the specified item}
\begin{algorithmic}
\REQUIRE A = randomly ordered array
\REQUIRE item = reference item
\OUTPUT ordinal position of item or -1 if the item does not exist
\FUNCTION{rank}{A, item}
    \STATE $r \gets -1$
    \FOR{$i \in A$}
        \IF{$i \leq$ item}
            \STATE $r \gets r + 1$
        \ENDIF
    \ENDFOR
    \RETURN{r}
\ENDFUNCTION
\end{algorithmic}
\end{algorithm}

Return to Exercises