这是上周的一个测验。我认为以下问题的答案是Line:3。但是,教练告诉我4号线比较好。我还是不明白为什么?并导致另一个问题,我怎么知道我的最佳增量?
我想问的第二个问题,如何使用Summations来表示下面运行代码的成本?我搜索了很多,而且我发现所有代码都发现代码的复杂性与此无关。
我希望你们清楚我的一切。
答案 0 :(得分:0)
当您将整数乘以2时,编译器会自动将其转换为右移操作(这非常有效)。此外,比较浮点数比比较整数更昂贵。由于第4行的执行次数与执行第3行的次数相同,因此第4行将是总成本的最佳代表。
代码的总费用
= total cost of comparing i with n and incrementing i +
total cost of comparing j with n and right shifting j +
total cost of comparing two floats +
total cost of incrementing a float
<= c1*n + c2*n*n/2 + c3*n*n/2 + c4\sum_{1 <= i <= n, 1 <= k <= n/2}d(i,2k),
where d(i, j) is 1 if array[i] > array[j] and 0 otherwise.
<= c1*n + c2*n^2 + c3n^2 + c4n^2
<= c*n^2 for some constant c