(a) State the time complexity of the following algorithm in terms of n. [1]
FOR i ← 1 TO n
FOR j ← 1 TO n
OUTPUT i * j
ENDFOR
ENDFOR(b) State the time complexity of a binary search on a sorted list of n items. [1]
(c) An algorithm with time complexity O(n²) takes 4 ms for n = 1000. Estimate the time it takes for n = 3000. Show your working. [2]
- (a) O(n²)(1)
- (b) O(log n)(1)
- (c) n is multiplied by 3, so time is multiplied by 3² = 9(1)
- (c) 4 × 9 = 36 ms(1)
- Answer: (a) O(n^2) (b) O(log n) (c) 36 ms
- Examiner tip: For O(n²), multiplying the input size by k multiplies the time by k², not by k.