算法4中数学模型练习题分析

Problem description:
How many array accesses does the following code fragment makes as  a function of n?
  (Assume the compiler does not optimize away any array accesses in the innermost loop).
以下的代码片段作为n的函数进行了多少次的数组访问?(假设编译器没有优化对最内层的循环中的任何数组)
int sum = 0;
for (int i = 0; i < n; i++)
    for (int j = i+1; j < n; j++)
        for (int k = 1; k < n; k = k*2)
            if (a[i] + a[j] >= a[k]) sum++;

~3n^2
~(3n^2)*lgn/2
~3n^3/2 
~3n^3

这种分析其实很简单,但是第一次做可能会迷糊。首先应该看最内层的循环,最内层的循环执行了lgn次,而这个循环体里每次进行了3次数组的访问。因此一次k-loop需要访问3lgn次数组访问。而最外面两层循环比较好算,是一个离散表达式 波浪线(tilde notation)表示舍掉低阶项消耗上的近似值。因此最后的结果便是
~(3n^2)*lgn/2

猜你喜欢

转载自blog.csdn.net/shendezhuti/article/details/78282139
今日推荐