如果我有一个数组 A = <0, 15, 5, 1, 0, 20, 25, 30, 35, 40>。当我编写代码来计算比较时,我对在哪里添加计数器感到困惑,因为我担心可能会重复计数。
尽管如此,它说有15个比较。我不确定这是否正确。真正的比较有多少?
int InsertionSort(int A[], int n)
{
int i, j, index, counter = 0;
for (i=1; i < n; i++)
{
index = A[i];
for (j=i-1;j >= 0 && A[j] > index;j--)
{
A[j + 1] = A[j];
counter++;
}
A[j+1] = index;
counter++;
}
return counter;
}
int main()
{
int A[]= {5,4,3,2,1};
int counter = 0;
int n =5;
counter = InsertionSort(A, n);
printf("%d",counter);
return 0;
}