I have two lists to sort using insertion sort:
How many comparisons does the insertion sort use to sort the list $n, n − 1, . . . , 2, 1$?
How many comparisons does the insertion sort use to sort the list $1, 2, . . . , n$?
I know that the answer for each respectively is:
- $1+1+...+1=\sum\limits_{i=1}^{n-1}1=n-1$
- $\frac{(n^2-n)}{2}$
I don't understand why the first does not have $O(n^2)$ complexity instead of $O(n)$? I guess we need the same amount of comparison for both. I am confused about what the series of numbers in both questions mean?
Insertion Sort Algorithm:
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}