标签:near IV int row ops follow span 4.6 code
question:
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:
a. N + N/2 + N/4 + ... 即N(等比求和)
b. 1 + 2 + 4 + 8 + ... 即N //和a一模一样,只是顺序反了
c. 外层lgN, 内层N,且互不影响,即NlgN
//官网答案
Answer: linear (N + N/2 + N/4 + ...); linear (1 + 2 + 4 + 8 + ...); linearithmic (the outer loop loops lg N times).
标签:near IV int row ops follow span 4.6 code
原文地址:https://www.cnblogs.com/w-j-c/p/9128147.html