1.4.6
阿新 • • 發佈:2018-06-03
In AC ++ AS run IT for mes follow
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).
1.4.6