• Home
  • Textbooks
  • AS and A Level OCR Computer Science
  • Algorithms

AS and A Level OCR Computer Science

PM Heathcote, RSU Heathcote, PG Online

Chapter 12

Algorithms - all with Video Answers

Educators


Section 59

Analysis and design of algorithms

Problem 1

Assuming a is an array of $n$ elements, compute the time complexity of the following algorithm.
Explain how you arrive at your answer.
duplicate $=$ False
for $i=0$ to $n-2$
for $j=i+1$ to $n-1$
$\quad$ if $a[i]=a[j]$ then duplicate = True
next $j$
next $i$
duplicate $=$ False
for $i=0$ to $n-2$
for $j=i+1$ to $n-1$
if $a[i]=a[j]$ then duplicate $=$ True
next $j$
next $i$

Check back soon!
01:15

Problem 2

(a) Complete the following table showing values of $f(n)$ :
\begin{tabular}{|c|l|l|l|l|c|}
\hline $\mathbf{n}$ & $\mathbf{1}$ & $\mathbf{2}$ & $\mathbf{4}$ & $\mathbf{8}$ & $\mathbf{1 2}$ \\
\hline $\mathbf{f}(\mathbf{n})=\mathbf{n}^2$ & 1 & 4 & & & \\
\hline $\mathbf{f}(\mathbf{n})=\mathbf{2}^{\mathrm{n}}$ & 2 & 4 & & & \\
\hline $\mathbf{f}(\mathbf{n})=\log _2 n$ & 0 & 1 & & & 3.585 \\
\hline $\mathbf{f}(\mathrm{n})=\mathrm{n} !$ & 1 & & & & $479,001,600$ \\
\hline
\end{tabular}
(b) Place the following algorithms in order of time complexity, with the most efficient algorithm first.
Algorithm A of time complexity $O(n)$
Algorithm $B$ of time complexity $O\left(2^n\right)$
Algorithm $\mathrm{C}$ of time complexity $O(\log n)$
Algorithm D of time complexity $O\left(n^2\right)$
Algorithm $E$ of time complexity $O(n !)$
Explain why algorithms with time complexity $O(n !)$ are generally considered not to be helpful in solving a problem. Under what circumstances would such an algorithm be considered?

Nick Johnson
Nick Johnson
Numerade Educator