Activity 4.5.2: Selection Sort
Consider the following algorithm on an array of numbers
$x_1, x_2, x_3, \dots, x_n$.
The element in the first position is compared to the $n - 1$
remaining elements; whenever one is found that is less,
the first element is swapped with it. Then the element in
the second position is compared with the remaining $n - 2$
elements. Whenever one is found that is less, the
elements are swapped. This continues until the $(n-1)$st
element; if it is out of order with the $n$th element, the
elements are swapped. The algorithm pseudocode is
shown below:
for $i \in \{1, 2, \dots, n - 1\}$ do
$\quad$ for $j \in \{i + 1, i + 2, \dots, n\}$ do
$\qquad$ if $x_i > x_j$ then swap $x_i$ and $x_j$
1. Step through this algorithm when applied to the array $x_1 = 9, x_2 = 4, x_3 = 7, x_4 = 1$. Record the values of the array every time they change.
2. In terms of $n$, how many comparisons does this algorithm make on an array of length $n$?