Consider the problem of sorting a list \(x_1,\dots,x_n\) of numbers in increasing order; this is equivalent to the problem of sorting words in alphabetical order which was discussed in the previous section. Here is a simple algorithm for achieving this, known as InsertionSort. For each \(i\geq1\text{,}\) the \(i\)th step of the algorithm will start with a list \(L=(y_1,\dots,y_{i-1})\) consisting of all of the numbers \(x_1,\dots,x_{i-1}\) in the correct order, and it will insert \(x_i\) into the appropriate location in \(L\text{.}\) So, when \(i=1\text{,}\) we start with the empty list \(L=()\) and insert \(x_1\) to yield the list \(L=(x_1)=(y_1)\text{.}\) In general, for \(i\geq2\text{,}\) we find the smallest index \(j\) such that \(y_{j+1}\geq x_i\) and insert \(x_i\) between \(y_j\) and \(y_{j+1}\text{;}\) if no such index exists, then we insert \(x_i\) at the end of the list. In the end, our output will be the list \((y_1,\dots,y_n)\) which will consist of all of the numbers \(x_1,\dots,x_n\) in increasing order.
Now, in order to judge the speed of this algorithm, we need to estimate the maximum number of elementary operations it will take. Clearly, the algorithm does not use any arithmetic operations. Also, the number of branching instructions is \(n\text{,}\) since it needs to “go back to the start” exactly \(n-1\) times and the final step of the algorithm consists of the branching instruction which stops the algorithm and outputs the result. On the \(i\)th step of the algorithm, the number \(x_i\) is compared with at most \(i-1\) other numbers in the list. So, the total number of comparisons is at most
\begin{equation*}
\sum_{i=1}^n(i-1) = \frac{n(n-1)}{2}.
\end{equation*}
So, the total number of elementary operations is \(\frac{n(n-1)}{2}+n = \frac{n(n+1)}{2}\text{.}\)
