State the time complexity in Big-O notation of each code fragment, where n = len(items).
(a)
for i in range(n):
for j in range(n):
count += 1[1]
(b)
i = n
while i > 1:
i = i // 2[1]
(c)
total = 0
for x in items:
total += x[1]
(d) Outline why the fragment in (b) is much more efficient than the fragment in (c) for very large n. [1]
- (a) O(n²) (accept O(n^2), O(n*n))(1)
- (b) O(log n) (accept O(log₂ n))(1)
- (c) O(n)(1)
- (d) In (b) i is halved each iteration, so the number of steps grows very slowly (about log₂ n, e.g. about 20 for a million) whereas in (c) the number of steps grows in direct proportion to n(1)
- Answer: (a) O(n²) (b) O(log n) (c) O(n)
- Examiner tip: Name the halving pattern for log n; saying 'it is faster' without relating step count to n earns nothing.