Exercise 1
Suppose List and List are two lists of numbers in increasing order.
(i)
Write an algorithm to find elements in List that are not present in List 2.
(ii)
Write an algorithm to find elements in List that are not present in List 1.
Not cross-checked
This solution has not been cross-checked against the answer printed in NCERT.
(i) Write List $\displaystyle 2$ as \(\displaystyle b_1<b_2<\cdots\).1. Start with an empty list-only-in-$\displaystyle 1$ and \(\displaystyle j=1\).
2. For each \(\displaystyle a\) in List $\displaystyle 1$, in order:
while List $\displaystyle 2$ is not used up and \(\displaystyle b_j<a\), increase \(\displaystyle j\) by $\displaystyle 1$;
if List $\displaystyle 2$ is used up or \(\displaystyle b_j>a\), add \(\displaystyle a\) to list-only-in-1.
Example:\[\text{List 1}=[2,4,6,8,10],\qquad \text{List 2}=[4,5,6,9,10,12] \]\[\begin{array}{c|c|l}
a & b_j & \text{action}\\ \hline
2 & 4 & 4>2:\ \text{add } 2\\
4 & 4 & \text{equal}\\
6 & 6 & \text{equal}\\
8 & 9 & 9>8:\ \text{add } 8\\
10 & 10 & \text{equal}
\end{array}
\]\[\text{list-only-in-1}=[2,8] \](ii) Interchange the two lists in the steps above. For the same example:\[\text{list-only-in-2}=[5,9,12] \]Answer: (i) for each \(\displaystyle a\) in List $\displaystyle 1$, move \(\displaystyle j\) forward in List $\displaystyle 2$ and keep \(\displaystyle a\) if \(\displaystyle b_j>a\) or List $\displaystyle 2$ is used up; example \(\displaystyle [2,8]\). (ii) the same with the lists interchanged; example \(\displaystyle [5,9,12]\).