We've already considered the case where the inputs to this function were already arranged into ascending order. What would happen if the inputs were almost, but not exactly, already sorted into ascending order?

For example, suppose that, on average, one out of n items is out of order. Then the probability of a
given input repeating the loop zero times would be p_{0} = (n-1)/n, and some single p_{i} would have probability 1/n, with all the other probabilities being zero.

Assuming the worst (because we want to find an upper bound), let's assume that the one out-of-order element is the very last one added, and that it actually gets inserted into position 0. Then we have

`p_0 = (n-1)/2, p_1 = 0, p_2 = 0, \ldots, p_{n-1} = 0,
p_n = 1/n`

So the average number of iterations would be given by

`k_{text{avg}} = \sum_{i=0}^{n} (i+1)p_i`

`\ \ \ = 1*{n-1}/n + (n + 1) * /n`

`\ \ \ = (2n)/n`

`\ \ \ = 2`

and the function is `O(k_{text{avg}}) = O(1)`

## In the Forum: