什么是反演?
给定一个数组arr [],如果arr [i]
发生O(n)倒置时,插入排序的时间复杂度是多少?
考虑以下插入排序函数。
/* Function to sort an array using insertion sort*/
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;
}
}
如果我们仔细看一下插入排序代码,我们会注意到while循环的每次迭代都会减少一个反转。仅当i> j并且arr [i]