Give the order of growth (as a function of N) of the running times of each of the following code fragments:
a
int sum = 0;
for (int n = N; n > 0; n /= 2)
for (int i = 0; i < n; i++)
sum++;
b
int sum = 0;
for (int i = 1; i < N; i *= 2)
for(int j = 0; j < i; j++)
sum++;
c
int sum = 0;
for (int i = 1; i < N; i *= 2)
for (int j = 0; j < N; j++)
sum++;
Answer: linear (N + N/2 + N/4 + …); linear (1 + 2 + 4 + 8 + …); linearithmic (the outer loop loops lg N times).
题b中,即为等比数列,依据等比数列公式,1+2+3+4…+N=2N-1~N,故为线性复杂度